c++建立普通的基类building,用来存储一座楼房的层数、房间数以及它的总平方数。建立派生类house,继承building,并存储卧室与浴室的数量,另外,建立派生类office,继承building,并存储灭火器与电话的数目。设计一主函数来测试以上类的用法
时间: 2024-05-08 18:18:55 浏览: 120
基类和派生类 面向对象程序设计 C++ 实验报告
好的,您的问题是关于面向对象编程的。首先,您需要定义基类building,该类包含楼房的层数、房间数以及总平方数。以下是一个可能的实现:
```c++
class Building {
public:
Building(int floors, int rooms, int totalArea) :
m_floors(floors), m_rooms(rooms), m_totalArea(totalArea) {}
int getFloors() const { return m_floors; }
int getRooms() const { return m_rooms; }
int getTotalArea() const { return m_totalArea; }
private:
int m_floors;
int m_rooms;
int m_totalArea;
};
```
接下来,您需要创建两个派生类,一个是house,另一个是office。派生类中需要额外的属性以及与基类相同的属性。以下代码可能会满足您的需求:
```c++
class House : public Building {
public:
House(int floors, int rooms, int totalArea, int bedrooms, int bathrooms) :
Building(floors, rooms, totalArea), m_bedrooms(bedrooms), m_bathrooms(bathrooms) {}
int getBedrooms() const { return m_bedrooms; }
int getBathrooms() const { return m_bathrooms; }
private:
int m_bedrooms;
int m_bathrooms;
};
class Office : public Building {
public:
Office(int floors, int rooms, int totalArea, int fireExtinguishers, int phones) :
Building(floors, rooms, totalArea), m_fireExtinguishers(fireExtinguishers), m_phones(phones) {}
int getFireExtinguishers() const { return m_fireExtinguishers; }
int getPhones() const { return m_phones; }
private:
int m_fireExtinguishers;
int m_phones;
};
```
最后,您需要设计一个主函数来测试这些类的使用。以下是一个可能的实现:
```c++
#include <iostream>
int main() {
Building b(10, 50, 5000);
std::cout << "Building has " << b.getFloors() << " floors, " << b.getRooms() << " rooms, and " << b.getTotalArea() << " total square feet.\n";
House h(2, 3, 1500, 3, 2);
std::cout << "House has " << h.getBedrooms() << " bedrooms and " << h.getBathrooms() << " bathrooms.\n";
Office o(5, 10, 10000, 20, 50);
std::cout << "Office has " << o.getFireExtinguishers() << " fire extinguishers and " << o.getPhones() << " phones.\n";
return 0;
}
```
此主函数创建了一个基类实例、一个house实例和一个office实例,并显示它们的属性。运行该程序应输出类似以下信息:
```
Building has 10 floors, 50 rooms, and 5000 total square feet.
House has 3 bedrooms and 2 bathrooms.
Office has 20 fire extinguishers and 50 phones.
```
希望这能真正解决您的问题!
阅读全文