#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;
}
上面是的程序把数据写入到文件里,但我想重新读取出来,可是这里有个问题,因为是用了多态,所以写入到文件里的数据有 A对象也有B对象的,但在读取,我不知道应该定义个什么类型来接收这些数据。 |