用c++建立一个基类Building,用来存储一座楼房的层数、房间数以及它的总平方英尺数。建立派生类Housing,继承Building,并存储下面的内容:卧室和浴室的数量,另外,建立派生类Office,继承Building,并存储灭火器和电话的数目。然后,编制应用程序,建立住宅楼对象和办公楼对象,并输出它们的有关数据。
时间: 2024-03-14 17:45:00 浏览: 105
基类和派生类 面向对象程序设计 C++ 实验报告
好的,根据您的问题,以下是 C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
class Building {
protected:
int floors; // 层数
int rooms; // 房间数
int totalArea; // 总平方英尺数
public:
Building(int f, int r, int a) {
floors = f;
rooms = r;
totalArea = a;
}
};
class Housing : public Building {
private:
int bedrooms; // 卧室数量
int bathrooms; // 浴室数量
public:
Housing(int f, int r, int a, int b, int bth) : Building(f, r, a) {
bedrooms = b;
bathrooms = bth;
}
void display() {
cout << "Housing:\nFloors: " << floors << "\nRooms: " << rooms << "\nTotal Area: " << totalArea << "\nBedrooms: " << bedrooms << "\nBathrooms: " << bathrooms << endl;
}
};
class Office : public Building {
private:
int fireExtinguishers; // 灭火器数目
int phones; // 电话数目
public:
Office(int f, int r, int a, int fe, int ph) : Building(f, r, a) {
fireExtinguishers = fe;
phones = ph;
}
void display() {
cout << "Office:\nFloors: " << floors << "\nRooms: " << rooms << "\nTotal Area: " << totalArea << "\nFire Extinguishers: " << fireExtinguishers << "\nPhones: " << phones << endl;
}
};
int main() {
Housing myHouse(2, 5, 2000, 3, 2);
Office myOffice(3, 10, 5000, 20, 15);
myHouse.display();
cout << endl;
myOffice.display();
return 0;
}
```
运行上述代码会得到以下输出:
```
Housing:
Floors: 2
Rooms: 5
Total Area: 2000
Bedrooms: 3
Bathrooms: 2
Office:
Floors: 3
Rooms: 10
Total Area: 5000
Fire Extinguishers: 20
Phones: 15
```
以上代码中,我们首先定义了一个基类 Building,其中包含了楼房的层数、房间数以及总平方英尺数,然后用 Housing 类和 Office 类继承自 Building 类,并增加了它们各自的特征。接下来,在主函数中,我们创建了一个住宅楼对象和一个办公楼对象,并分别调用它们的 display 函数来输出它们的数据。
阅读全文