说明:
基类Substance
派生类 H 和O 类 继承Substance
HxOx类多重继承了H类和O类
1) 在没有使用虚继承的时候,代码如下(会报错)
#include <iostream>
using namespace std;
class Substance{
protected:
int atomicity; //原子数
public:
Substance(int atomicity = 0){
Substance::atomicity = atomicity;
}
virtual void ShowInfo() = 0; //纯虚函数
};
//这里H直接继承Substance类,不使用虚拟继承
class H : public Substance{
protected:
bool flammable; //可燃的
public:
H(int atomicity = 0,bool flammable = true) : Substance(atomicity){
H::flammable = flammable;
}
void ShowInfo(){
cout << "氢元素" << endl;
}
};
//这里O直接继承Substance类,不使用虚拟继承
class O : public Substance{
protected:
bool breathable; //可呼吸的
public:
O(int atomicity = 0,bool breathable = true) : Substance(atomicity){
O::breathable = breathable;
}
void ShowInfo(){
cout << "氧元素" << endl;
}
};
class HxOx : public H , public O{
public:
HxOx(int atomicity,bool flammable,bool breathable):
Substance(atomicity),H(atomicity,flammable),O(atomicity,breathable){}
void ShowInfo(){
cout << "氢氧化合物" << endl;
}
void ShowDetail(){
cout << "原子数: " << atomicity << endl;
cout << "是否可燃: " << flammable << endl;
cout << "是否可吸入: " << breathable << endl;
}
};
int main() {
HxOx a(3,false,false);
a.ShowInfo();
a.ShowDetail();
return 0;
}
出错原因:
在HxOx类多重继承H和O类时,由于出现了Substance的两个副本,编译器无法找到究竟哪一个atomicity才是应该用的,所以出现了如下的错误
2) 使用了虚拟继承的方法,代码如下
#include <iostream>
using namespace std;
class Substance{
protected:
int atomicity; //原子数
public:
Substance(int atomicity = 0){
Substance::atomicity = atomicity;
}
virtual void ShowInfo() = 0; //纯虚函数
};
//这里H继承Substance类时使用虚拟继承
class H : virtual public Substance{
protected:
bool flammable; //可燃的
public:
H(int atomicity = 0,bool flammable = true) : Substance(atomicity){
H::flammable = flammable;
}
void ShowInfo(){
cout << "氢元素" << endl;
}
};
//这里O继承Substance类时使用虚拟继承
class O : virtual public Substance{
protected:
bool breathable; //可呼吸的
public:
O(int atomicity = 0,bool breathable = true) : Substance(atomicity){
O::breathable = breathable;
}
void ShowInfo(){
cout << "氧元素" << endl;
}
};
class HxOx : public H , public O{
public:
HxOx(int atomicity,bool flammable,bool breathable):
Substance(atomicity),H(atomicity,flammable),O(atomicity,breathable){}
void ShowInfo(){
cout << "氢氧化合物" << endl;
}
void ShowDetail(){
cout << "原子数: " << atomicity << endl;
cout << "是否可燃: " << flammable << endl;
cout << "是否可吸入: " << breathable << endl;
}
};
int main() {
HxOx a(3,false,false);
a.ShowInfo();
a.ShowDetail();
return 0;
}
输出:
氢氧化合物
原子数: 3
是否可燃: 0
是否可吸入: 0
虚拟继承的机制:
为什么继承的时候:virtual public Substance 就不会出错呢?
其实这是因为,在多重继承的时候使用了这种虚拟继承方法之后,编译器只会创建一个Substance的副本,所以在O和H继承Substance的时候只创建了一个副本,因此就不会再有成员可能的二义性出现了