避免调用基础构造函数2次

Che*_*ems 1 c++ inheritance

假设我有几个继承的类.

#include <iostream>

struct A {
    A() {std::cout << "a";}
};

struct B : A {};
struct C : A {};

struct D : B, C {};

int main {
    D d;
}
Run Code Online (Sandbox Code Playgroud)

在执行程序时,正如预期的那样,我看到构造了两个A对象,一个用于B,另一个用于创建D对象时构造的C对象.谁,我怎么能不创建两个A对象?我希望使用相同的A对象来创建B和C对象.这可能吗?

Tar*_*ama 7

如果BC都使用虚拟继承A,那么将仅存在用于每个单个基类对象D对象:

struct B : virtual A {};
struct C : virtual A {};

//...
D d; //prints "a" rather than "aa" 
Run Code Online (Sandbox Code Playgroud)

现场演示