+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2020-05(10)

2020-06(45)

2020-07(33)

2020-08(45)

2020-09(74)

c++之diamond problem

发布于2021-04-26 00:37     阅读(249)     评论(0)     点赞(6)     收藏(4)


0

1

2

3

4

5

6

7

8

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?

例子:

  1. class Base {
  2. public:
  3. virtual void f() {}
  4. };
  5. class A :public Base {
  6. public:
  7. virtual void f() {}
  8. };
  9. class B :public Base {
  10. public:
  11. virtual void f() {}
  12. };
  13. class C :public A, public B {
  14. public:
  15. //virtual void f() {} //必须显式地定义该函数才可以编译通过
  16. };
  17. int main() {
  18. C objC;
  19. objC.f();//编译器报错
  20. return 1;
  21. }

main函数中objC.f();会报错


大多数现代编程语言对多重继承避而远之了, PHP 、Swift、Java 都是不支持 ,因为多重继承增加了程序的复杂性和含糊性,例如容易导致该菱形缺陷。但是Python支持多重继承的,Python 对菱形问题的处理使用方法解析顺序(Method Resolution Order,MRO)。

  1. class A:
  2. def test(self):
  3. print("test A")
  4. class B(A):
  5. def test(self):
  6. print("test B")
  7. class C(A):
  8. def test(self):
  9. print("test C")
  10. class D(B, C):
  11. pass
  12. d = D()
  13. d.test() # 此时输出 test B

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

原文链接:https://blog.csdn.net/qq_35865125/article/details/116108205

0

1

2

3

4

5

6

7

8

9



所属网站分类: 技术文章 > 博客

作者:83748wuw

链接: https://www.pythonheidong.com/blog/article/953645/f01ee407add2351c4655/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

6 0
收藏该文
已收藏

评论内容:(最多支持255个字符)