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

标签 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++ - 默认构造函数和虚拟继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3524019/

相关文章:

c++ - C++ STL set_symmetry_difference 的正确用法?

c++ - 初始化完成 opengl 支持可用

c++ - 为什么 typedef 不能与 static 一起使用?

c++ - Clang 4.6.2,使用 shared_ptr

C++ 简单的刽子手游戏

c++ - 请帮助使用 MFC CMap(或 std::map)

c++ - 如何将 QSerialPort 模块添加到 CMake 中?

c++ - 在 C++ 中清理一串标点符号

c++ - 如何为类 union 类编写析构函数

c++ - 无法从花括号初始化列表构造 constexpr 数组