多继承中的菱形问题
此时D会继承两个temp
#include<iostream>
#include<Windows.h>
using namespace std;
class A {
public:
A() {
this->temp = 10;
}
int temp;
};
class B :public A { //B继承的temp经过构造函数初始化值为10
};
class C :public A { //C继承的temp经过构造函数初始化值为10
};
class D :public B, public C { //D会继承两个temp B::temp和C::temp
public:
D(int temp) {
this->B::temp = temp; //B::temp = 15
}
int getTemp() {
return this->C::temp; //C::temp = 10
}
};
int main() {
D d(15);
cout << d.getTemp() << endl;
system("pause");
return 0;
}
解决方法:虚拟继承
#include<iostream>
#include<Windows.h>
using namespace std;
class A {
public:
A() {
this->temp = 10;
}
int temp;
};
class B :virtual public A { //虚拟继承
};
class C :virtual public A { //虚拟继承
};
class D :public B, public C { //D将只会继承一个temp
public:
D(int temp) {
this->temp = temp;
}
int getTemp() {
return this->temp;
}
};
int main() {
D d(15);
cout << d.getTemp() << endl;
system("pause");
return 0;
}
小结:
尽量不要使用多重继承