题目:设计一个空调类airCondition,其中包括:
数据成员:品牌(要求char* 类型)、颜色、攻率、开关状态、设定温度;
构造函数:对品牌、颜色、攻率、设定温度赋初值;
要求1.写出复制构造函数(参数必须被const 修饰),赋值运算符重载函数
2.要求有一定有默认构造函数的生成(=default的使用)
析构函数:用户自定义(注意动态申请的资源的释放);
成员函数:切换开关状态、升温、降温。
主函数中要求至少创建三个对象,其中之一用复制构造函数初始化,另外一个创建后用赋值运算符赋值;
具体信息如:格力、白色、2匹、25度等等。调用其“切换开关状态”函数打开空调,调用其“降温”函数调整温度为20度,并打印空调状态和目前设定的温度到屏幕。
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
#define OPEN true
#define CLOSE false
class Aircondition
{
private:
char *g_brand;
string g_colour;
double g_power;
public:
float g_tempreture;
bool status; // 开关状态
public:
Aircondition() = default;
Aircondition(char *brand, string colour, double power, float tempreture)
{
g_brand = new char[strlen(brand) + 1];
strcpy(g_brand, brand);
g_colour = colour;
g_power = power;
g_tempreture = tempreture;
status = false;
}
// 复制构造
Aircondition(const Aircondition &a)
{
g_brand = new char[strlen(a.g_brand) + 1];
strcpy(g_brand, a.g_brand);
g_colour = a.g_colour;
g_power = a.g_power;
g_tempreture = a.g_tempreture;
status = a.status;
}
// 赋值运算符重载
Aircondition &operator=(const Aircondition &a)
{
g_brand = new char[strlen(a.g_brand) + 1];
strcpy(g_brand, a.g_brand);
g_colour = a.g_colour;
g_power = a.g_power;
g_tempreture = a.g_tempreture;
status = a.status;
}
~Aircondition()
{
delete[] g_brand;
}
void show()
{
cout << "品牌: " << g_brand << endl;
cout << "颜色: " << g_colour << endl;
cout << "功率: " << g_power << "匹" << endl;
cout << "设定温度: " << g_tempreture << "度" << endl;
}
bool Switch()
{
status = !status;
if (status == true)
cout << "空调启动" << endl;
else
cout << "空调关闭" << endl;
}
void tempreture_turnup(int t)
{
g_tempreture = g_tempreture + t;
}
void tempreture_turndown(int t)
{
g_tempreture = g_tempreture - t;
}
};
int main()
{
Aircondition a("格力", "白色", 2, 25);
a.show();
a.Switch();
if (a.status == OPEN)
{
int aim_tempreture;
cout << "目标温度:";
cin >> aim_tempreture;
if (aim_tempreture > a.g_tempreture)
a.tempreture_turnup(aim_tempreture - a.g_tempreture);
else if (aim_tempreture < a.g_tempreture)
a.tempreture_turndown(a.g_tempreture - aim_tempreture);
}
a.show();
Aircondition b(a); //复制构造
b.show();
Aircondition c = b; // 赋值重载
c.show();
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!