作业要求:
代码:
#include <iostream>
using namespace std;
//沙发 类
class Sofa
{
private:
string sitting; //是否可坐
double *cost; //花费
public:
//无参构造函数
Sofa(){}
//有参构造函数
Sofa(string s,double c):sitting(s),cost(new double(c))
{cout << "Sofa构造完成" << endl;}
//拷贝构造函数
Sofa(const Sofa &o):sitting(o.sitting),cost(o.cost)
{cout << "Sofa拷贝完成" << endl;}
//析构函数
~Sofa()
{
delete(cost);
cost = nullptr;
cout << "Sofa析构完成" << endl;
}
//拷贝赋值函数
Sofa &operator=(const Sofa &o)
{
if(this != &o)
{
sitting = o.sitting;
cost = o.cost;
cout << "Sofa复制完成" << endl;
}
return *this;
}
//展示函数
void show()
{
cout << sitting << " " << *cost << endl;
}
};
//床 类
class Bed
{
private:
string sleep;
int *size;
public:
//无参构造函数
Bed(){}
//有参构造函数
Bed(string s,int size):sleep(s),size(new int(size))
{cout << "Bed构造完成" << endl;}
//拷贝构造函数
Bed(const Bed &o):sleep(o.sleep),size(o.size)
{cout << "Bed拷贝完成" << endl;}
//析构函数
~Bed()
{
delete(size);
size = nullptr;
cout << "Bed析构完成" << endl;
}
//拷贝赋值函数
Bed &operator=(const Bed &o)
{
if(this != &o)
{
sleep = o.sleep;
size = o.size;
cout << "Bed复制完成" << endl;
}
return *this;
}
//展示函数
void show()
{
cout << sleep << " " << *size << endl;
}
};
//沙发床 类 以公有继承方式继承于沙发和床
class Sofa_bed:public Sofa,public Bed
{
private:
string color;
public:
//无参构造函数
Sofa_bed(){}
//有参构造函数
Sofa_bed(string col, string sit, double cost,string sle,int size):Sofa(sit,cost),Bed(sle,size),color(col)
{
cout << "Sofa_bed构造完成" << endl;
}
//拷贝构造函数
Sofa_bed(const Sofa_bed &o):Sofa(o),Bed(o),color(o.color)
{
cout << "Sofa_bed拷贝完成" << endl;
}
//析构函数
~Sofa_bed()
{
cout << "Sofa_bed析构完成" << endl;
}
//拷贝赋值函数
Sofa_bed &operator=(const Sofa_bed &o)
{
if(this != &o)
{
color = o.color;
Sofa::operator=(o);
Bed::operator=(o);
cout << "Sofa_bed复制完成" << endl;
}
return *this;
}
//展示函数
void show()
{
Sofa::show();
Bed::show();
cout << color << endl;
}
};
int main()
{
Sofa_bed bs("white", "可坐", 999,"可睡",100);
cout << "****************************" << endl;
bs.Sofa::show();
cout << "****************************" << endl;
bs.Bed::show();
cout << "****************************" << endl;
bs.show();
return 0;
}
代码运行效果图:
思维导图: