c++ 默认构造函数和虚拟继承

是否可以有虚拟继承类不提供默认构造函数?

目前的菱形图(最简单的只有没有默认构造函数的变化)不编译(g 4.4.3)。

class A {
 public: 
  A(int ) {}
};
class B : virtual public A {
 public:
  B(int i) : A(i) {}
};
class C : virtual public A {
 public:
  C(int i) : A(i) {}
};
class D : public B, public C {
 public:
  D(int i) : B(i), C(i) {}
};

谢谢,
弗朗切斯科

最佳答案
你需要在这里明确地调用A的构造函数

 D(int i) : A(i), B(i), C(i) {}

virtual base classes are special in that they are initialized by the most derived class and not by any intermediate base classes that inherits from the virtual base. Which of the potential multiple initializers would the correct choice for initializing the one base?

If the most derived class being constructed does not list it in its member initalization list then the virtual base class is initialized with its default constructor which must exist and be accessible.

here无耻的复制:-)

转载注明原文:c++ 默认构造函数和虚拟继承 - 代码日志