c++ day5
完成沙发床的多继承,包含指针成员!
#include <iostream>
using namespace std;
class Sofa
{
private:
string siting;
int *num;//个数,指针成员
public:
Sofa(){cout << "SOfa::无参构造函数" << endl;}//无参构造
Sofa(string siting,int num):siting(siting),num(new int(num))//有参构造
{
cout << "Sofa::有参构造函数" << endl;
}
Sofa(const Sofa &other):siting(other.siting),num(new int(*(other.num)))//拷贝构造
{
cout << "Sofa::拷贝构造函数" << endl;
}
Sofa &operator=(const Sofa &other)//拷贝赋值
{
if (this!=&other)
{
siting=other.siting;
num=new int(*(other.num));
}
cout << "SOfa拷贝赋值函数" << endl;
return *this;
}
~Sofa()
{
delete num;
cout << "sofa::析构函数" << endl;
}
void show()
{
cout << "siting=" << siting << endl;
cout << "num=" << *num << endl;
}
};
class Bed
{
private:
string sleeping;
int * area;//面积,指针成员
public:
Bed(){cout << "Bed::无参构造函数" << endl;}//无参构造
Bed(string sleeping,int area):sleeping(sleeping),area(new int(area))//有参构造
{
cout << "Bed::有参构造函数" << endl;
}
Bed(const Bed &other):sleeping(other.sleeping),area(new int(*(other.area)))//拷贝构造
{
cout << "Bed::拷贝构造函数" << endl;
}
Bed &operator=(const Bed &other)//拷贝赋值
{
if (this!=&other)
{
sleeping=other.sleeping;
area=new int(*(other.area));
}
cout << "Bed::拷贝赋值函数" << endl;
return *this;
}
~Bed()//析构函数
{
delete area;
cout << "Bed::析构函数" << endl;
}
void show()
{
cout << "sleeping=" << sleeping << endl;
cout << "arae=" << *area << endl;
}
};
class Sofa_Bed:public Sofa,public Bed
{
private:
string color;
public:
Sofa_Bed(){cout << "SOFA_Bed::无参构造函数" << endl;}
Sofa_Bed(string color,string siting,int num,string sleeping,int area):Sofa(siting,num),Bed(sleeping,area),color(color)
{
cout << "Sofa_Bed::有参构造函数" << endl;
}
Sofa_Bed(const Sofa_Bed &other):Sofa(other),Bed(other),color(other.color)
{
cout << "Sofa_Bed::拷贝构造函数" << endl;
}
Sofa_Bed &operator=(const Sofa_Bed &other)
{
if(this!=&other)
{
color=other.color;
Sofa::operator=(other);
Bed::operator=(other);
}
cout << "Sofa_Bed::拷贝赋值函数" << endl;
return *this;
}
~Sofa_Bed()
{
cout << "Sofa_Bed::析构函数" << endl;
}
void show()
{
Sofa::show();
Bed::show();
cout << "color= " << color << endl;
}
};
int main()
{
Sofa_Bed bs("yellow","可坐",2,"可睡",20);
cout << "-------------------------" << endl;
bs.Sofa::show();
cout << "-------------------------" << endl;
bs.Bed::show();
cout << "-------------------------" << endl;
bs.show();
return 0;
}