多继承代码实现沙发床
cpp
#include <iostream>
using namespace std;
class Sofa {
private:
int h;
public:
Sofa() {
cout << "Sofa无参构造" << endl;
}
Sofa(int h): h(h) {
cout << "Sofa有参构造" << endl;
}
Sofa(const Sofa& other): h(other.h) {
cout << "Sofa拷贝构造" << endl;
}
Sofa& operator=(const Sofa& other) {
cout << "Sofa赋值拷贝" << endl;
h = other.h;
return *this;
}
~Sofa() {
cout << "Sofa析构函数" << endl;
}
};
class Bad {
private:
int w;
public:
Bad() {
cout << "Bad无参构造" << endl;
}
Bad(int w): w(w) {
cout << "Bad有参构造" << endl;
}
Bad(const Bad& other): w(other.w) {
cout << "Bad拷贝构造" << endl;
}
Bad& operator=(const Bad& other) {
cout << "Bad赋值拷贝" << endl;
w = other.w;
return *this;
}
~Bad() {
cout << "Bad析构函数" << endl;
}
};
class Sofa_Bad: public Sofa, protected Bad {
private:
string name;
public:
Sofa_Bad() {
cout << "Sofa_Bad无参构造" << endl;
}
Sofa_Bad(string name, int h, int w): Sofa(h), Bad(w), name(name) {
cout << "Sofa_Bad有参构造" << endl;
}
Sofa_Bad(const Sofa_Bad& other): Sofa(other), Bad(other), name(other.name) {
cout << "Sofa_Bad拷贝构造" << endl;
}
Sofa_Bad& operator=(const Sofa_Bad& other) {
Sofa::operator=(other);
Bad::operator=(other);
name = other.name;
cout << "Sofa_Bad赋值拷贝" << endl;
return *this;
}
~Sofa_Bad() {
cout << "Sofa_Bad析构函数" << endl;
}
};
int main() {
Sofa_Bad s1;
Sofa_Bad s2("aaaa", 100, 200);
Sofa_Bad s3(s2);
s1 = s3;
return 0;
}