c++之diamond problem

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

python的MRO方法: https://makina-corpus.com/blog/metier/2014/python-tutorial-understanding-python-mro-class-search-path

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

First Snowflakes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值