沙发床的多继承
代码:
#include <iostream>
using namespace std;
//封装 沙发 类
class Sofa
{
private:
string sitting;
double *size;
public:
//无参构造函数
Sofa() {cout << "Sofa::无参构造函数" << endl;}
//有参构造函数
Sofa(string s,double si):sitting(s),size(new double(si))
{cout << "Sofa::有参构造函数" << endl;}
//拷贝构造函数
Sofa(const Sofa &other):sitting(other.sitting),size(other.size)
{
cout << "Sofa::拷贝构造函数" << endl;
}
//拷贝赋值函数
Sofa &operator=(const Sofa &other)
{
if(this != &other)
{
cout << "Sofa::拷贝赋值函数" << endl;
this->sitting = other.sitting;
this->size = other.size;
}
return *this;
}
//析构函数
~Sofa()
{
delete(size);
size = nullptr;
cout << "Sofa::析构函数" << endl;
}
void show()
{
cout << sitting << " " << *size << endl;
}
};
//封装 床 类
class Bed
{
private:
string sleep;
public:
//无参构造函数
Bed() {cout << "Bed::无参构造函数" << endl;}
//有参构造函数
Bed(string s):sleep(s)
{cout << "Bed::有参构造函数" << endl;}
//拷贝构造函数
Bed(const Bed &other):sleep(other.sleep)
{
cout << "Bed::拷贝构造函数" << endl;
}
//拷贝赋值函数
Bed &operator=(const Bed &other)
{
cout << "Bed::拷贝赋值函数" << endl;
this->sleep = other.sleep;
return *this;
}
//析构函数
~Bed()
{
cout << "Bed::析构函数" << endl;
}
void show()
{
cout << sleep << endl;
}
};
//封装 沙发床 类 共有继承沙发和床
class Sofa_bed:public Sofa,public Bed
{
private:
string color;
public:
//无参构造函数
Sofa_bed(){cout << "Sofa_bed::无参构造函数" << endl;}
//有参构造函数
Sofa_bed(string s, double size,string sl, string c):Sofa(s,size), Bed(sl),color(c)
{
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)
{
cout << "Sofa::拷贝赋值函数" << endl;
this->color = other.color;
this->Sofa::operator=(other);
this->Bed::operator=(other);
return *this;
}
//析构函数
~Sofa_bed()
{
cout << "Sofa_bed::析构函数" << endl;
}
void show()
{
Sofa::show();
Bed::show();
cout << color << endl;
}
};
int main()
{
Sofa_bed sb("可以坐", 180, "可以睡", "灰不溜秋");
cout << "++++++++++++++++++++++++++++++++++++++" << endl;
sb.Sofa::show();
cout << "++++++++++++++++++++++++++++++++++++++" << endl;
sb.Bed::show();
cout << "++++++++++++++++++++++++++++++++++++++" << endl;
sb.show();
cout << "++++++++++++++++++++++++++++++++++++++" << endl;
return 0;
}
运行效果图:
思维导图
原文地址:https://blog.csdn.net/qq_65427718/article/details/134791696
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_42120.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。