64,646
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class A
{
private:
int i;
public:
A()
{
i = 10;
}
virtual void show()
{
cout << i << endl;
}
virtual void file(ofstream &of)
{
of << i << endl;
}
};
class B:public A
{
private:
string str;
public:
B()
{
str = "yuzengyuan";
}
void show()
{
A::show();
cout << str << endl;
}
void file(ofstream &of)
{
A::file(of);
of << str << endl;
}
};
class ABFamily
{
public:
static A* FamilyAB(int i)
{
A* q;
if (i == 1)
{
q = new A();
}
else
{
q = new B();
}
return q;
}
};
int main()
{
A* p[10];
int temp;
for (int i = 0; i < 10; i++)
{
cout << "请输入1-2数字: ";
cin >> temp;
p[i] = ABFamily::FamilyAB(temp);
}
for (i = 0; i < 10; i++) //把数据向文件里输出
{
ofstream file("1.txt", ios::app);
p[i]->file(file);
file.close();
}
for (i = 0; i < 10; i++) //释放内存
{
delete p[i];
}
cout << "程序完成!\n";
return 0;
}
// virtual_test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class A
{
private:
int i;
public:
A()
{
i = 10;
}
virtual void show()
{
cout << i << endl;
}
virtual void file(ofstream &of)
{
of << 1<< " "<<i << endl;
}
};
class B:public A
{
private:
string str;
public:
B()
{
str = "yuzengyuan";
}
void show()
{
A::show();
cout << str << endl;
}
void file(ofstream &of)
{
//A::file(of);
of <<2<<" "<<str << endl;
}
};
class ABFamily
{
public:
static A* FamilyAB(int i)
{
A* q;
if (i == 1)
{
q = new A();
}
else
{
q = new B();
}
return q;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
A* p[10];
int temp;
for (int i = 0; i < 10; i++)
{
cout << "请输入1-2数字: ";
cin >> temp;
p[i] = ABFamily::FamilyAB(temp);
}
ofstream file("./1.txt", ios::app);
if(file.fail())
std::cout<<"open error!"<<std::endl;
for (int i = 0; i < 10; i++) //把数据向文件里输出
{
p[i]->file(file);
}
file.close();
int pause;
cin>>pause;
for (int i = 0; i < 10; i++) //释放内存
{
delete p[i];
}
cout << "程序完成!\n";
return 0;
}