题目:
定义一个抽象类Structure(含有纯虚函数type函数,用以显示当前结构的类型; 含有show函数),
在此基础上派生出Building类, 用来存储一座楼房的层数、房间数以及它的总平方米数。 建立派生
类House,继承Building类,并存储下面的内容:卧室与浴室的数量。另外,建立派生类Office,继承
Building类,并存储灭火器与电话的个数。要求定义各个类的数据成员,成员函数(包括构造函数、
析构函数、显示各数据成员的show()函数,type()函数)。
(1)在完成上述类的基础上,在main函数中定义相应的对象,并测试所有的函数功能。
(2)在main()中,用Office类定义一个对象,请分析此时调用构造函数的顺序和析构函数的顺序。
(3)实现Structure类族中show()函数的动态多态性,要求要在每个层级都实现,并调用测试。
(4)在Office类中重载运算符“<<”,以便通过它来直接对Office类对象内容直接输出。
(5)调用“<<”运算符将Office对象的信息输出到文本文件“d:\\office.txt”中。
程序:
class Building :public Structure {
Building(int f = 1, int r = 0, int s = 0) {
cout << "the constructor function of Building has been called" << endl;
cout << "the destructor function of Building has been called" << endl;
cout << "The type is Building" << endl;
cout << "floor:" << floor << endl;
cout << "room:" << room << endl;
cout << "square:" << square << "m^2" << endl;
class House :public Building {
House(int floor = 1, int room = 0, int square = 0, int bedroom = 0, int bathroom = 0)
:Building(floor, room, square) {
this->bathroom = bathroom;
cout << "The type is House" << endl;
cout << "floor:" << floor << endl;
cout << "room:" << room << endl;
cout << "bedroom:" << bedroom << endl;
cout << "bathroom" << bathroom << endl;
cout << "square:" << square << "m^2" << endl;
class Office :public Building {
Office(int floor = 1, int room = 0, int square = 0, int hydrant = 0, int telephone = 0)
:Building(floor, room, square) {
this->telephone = telephone;
cout << "the constructor function of Office has been called" << endl;
cout << "The destructor function of Office has been called" << endl;
friend void operator<<(ostream&, Office&);
cout << "The type is Office" << endl;
cout << "floor:" << floor << endl;
cout << "room:" << room << endl;
cout << "hydrant:" << hydrant << endl;
cout << "telephone" << telephone << endl;
cout << "square:" << square << "m^2" << endl;
ofstream outfile("d:\\office.txt", ios::out);
cerr << "OPEN ERROR!" << endl;
outfile << "floor:" << floor << endl;
outfile << "room:" << room << endl;
outfile << "hydrant:" << hydrant << endl;
outfile << "telephone" << telephone << endl;
outfile << "square:" << square << "m^2" << endl;
void operator <<(ostream& output, Office& of) {
cout << "floor:" << of.floor << endl;
cout << "room:" << of.room << endl;
cout << "hydrant:" << of.hydrant << endl;
cout << "telephone" << of.telephone << endl;
cout << "square:" << of.square << "m^2" << endl;
House ho(2, 4, 100, 3, 2);
Office of(3, 10, 300, 5, 4);
结果: