#include <iostream>
using namespace std;
class CRoom
{
public:
char* name;
int number;
// 设置价格
void SetPrice(int t_price)
{
price = t_price;
}
// 获取价格
int GetPrice()
{
return price;
}
// 构造函数
CRoom(const char* t_name, int t_number, int t_price)
{
int len = strlen(t_name);
name = new char[len + 1]{ 0 };
memset(name, 0, len + 1);
strcpy(name, t_name);
number = t_number;
price = t_price;
}
// 析构函数
~CRoom()
{
delete[] name;
}
private:
int price;
};
class CStarRoom : public CRoom
{
public:
int star;
// 子类构造函数
CStarRoom(int t_star) : CRoom("HuiCui", 9999, 9999)
{
star = t_star;
}
};
int main()
{
// 对象初始化
CStarRoom room(5);
// 输出结果
cout << "酒店名字:" << room.name << endl;
cout << "酒店价格:" << room.GetPrice() << endl;
cout << "酒店房号:" << room.number << endl;
cout << "酒店星级:" << room.star << endl;
return 0;
}
【千律】C++基础:子类的构造函数和析构函数
最新推荐文章于 2022-08-27 21:56:04 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)