C++的多重继承是如何实现的?

21 c++ compiler-construction inheritance language-implementation multiple-inheritance

单继承很容易实现.例如,在C中,继承可以模拟为:

struct Base { int a; }
struct Descendant { Base parent; int b; }
Run Code Online (Sandbox Code Playgroud)

但是对于多重继承,编译器必须在新构造的类中安排多个父类.怎么做?

我看到的问题是:父母应该安排在AB或BA中,还是以其他方式安排?然后,如果我做演员:

SecondBase * base = (SecondBase *) &object_with_base1_and_base2_parents;
Run Code Online (Sandbox Code Playgroud)

编译器必须考虑是否更改原始指针.虚拟化需要类似的棘手的事情.

Bra*_*lor 10

以下来自C++创建者的文章描述了多重继承的可能实现:

C++的多重继承 - Bjarne Stroustrup

  • 备选链接:http://citeseerx.ist.psu.edu/viewdoc/download?doi = 10.1.1.23.4735 &rep =rep1&type = pdf (3认同)

Nem*_*vic 5

一篇关于它是如何在VC++中实现的这篇非常古老的MSDN文章.


Mic*_*urr 5

然后,如果我做演员:

SecondBase base = (SecondBase *) object_with_base1_and_base2_parents;
Run Code Online (Sandbox Code Playgroud)

编译器必须考虑是否更改原始指针.与虚拟相似的棘手事物.

使用非虚拟继承,这不像你想象的那么棘手 - 在编译强制转换时,编译器知道派生类的确切布局(毕竟,编译器完成了布局).通常所发生的一切都是从派生类指针中添加/减去固定偏移量(对于其中一个基类可能为零).

利用虚拟继承,它可能有点复杂 - 它可能涉及从vtbl(或类似)获取偏移量.

Stan Lippman的书"Inside the C++ Object Model"非常好地描述了这些东西可能(通常实际上)的工作方式.