class Base中定义virtual函数,virtual void f(); class A和class B继承自class Base,并重写了基类的虚函数virtual void f(); class C继承自A和B, 如果class C中不实现 virtual void f()的话,编译器会报错,因为,不清楚class C使用A的还是B的f();
Diamond problem:
The "diamond problem" (sometimes referred to as the "deadly diamond of death") is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
例子:
class Base {
public:
virtual void f() {}
};
class A :public Base {
public:
virtual void f() {}
};
class B :public Base {
public:
virtual void f() {}
};
class C :public A, public B {
public:
//virtual void f() {} //必须显式地定义该函数才可以编译通过
};
int main() {
C objC;
objC.f();//编译器报错
return 1;
}
main函数中objC.f();会报错。
大多数现代编程语言对多重继承避而远之了, PHP 、Swift、Java 都是不支持 ,因为多重继承增加了程序的复杂性和含糊性,例如容易导致该菱形缺陷。但是Python支持多重继承的,Python 对菱形问题的处理使用方法解析顺序(Method Resolution Order,MRO)。
class A:
def test(self):
print("test A")
class B(A):
def test(self):
print("test B")
class C(A):
def test(self):
print("test C")
class D(B, C):
pass
d = D()
d.test() # 此时输出 test B