主页 > 电脑硬件  > 

C++12.4

C++12.4
沙发床的多继承 多继承代码实现沙发床沙发床继承于沙发和床  代码: #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; } 运行效果图:

思维导图

标签:

C++12.4由讯客互联电脑硬件栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“C++12.4