简体   繁体   English

c++ 虚拟 inheritance

[英]c++ virtual inheritance

Problem:问题:

class Base {
public:
  Base(Base* pParent);
  /* implements basic stuff */
};

class A : virtual public Base {
public:
  A(A* pParent) : Base(pParent) {}
  /* ... */
};

class B : virtual public Base {
public:
  B(B* pParent) : Base(pParent) {}
  /* ... */
};

class C : public A, public B {
public:
  C(C* pParent) : A(pParent), B(pParent) {} // - Compilation error here
  /* ... */
};

At the position given, gcc complains that it cannot match function call to Base(), ie the default constructor.在给定的 position 中,gcc 抱怨它无法匹配 function 对 Base() 的调用,即默认构造函数。 But C doesn't inherit directly from Base, only through A and B. So why does gcc complain here?但是 C 并不直接从 Base 继承,只能通过 A 和 B 继承。那么为什么 gcc 会在这里抱怨呢?

Ideas?想法? TIA /Rob TIA /罗伯

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. virtual基类的特殊之处在于它们由最派生的类初始化,而不是由从虚拟基类继承的任何中间基类初始化。 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. 如果正在构造的派生程度最大的类未在其成员初始化列表中列出该类,则将使用必须存在且可访问的默认构造函数来初始化虚拟基类。

Note that a virtual base identifier is allowed to be use in a constructor's initializer list even if it is not a direct base of the class in question. 请注意,即使虚拟基标识符不是所讨论类的直接基,也可以在构造函数的初始化列表中使用它。

You need to explicitly call the constructor for Base from C: 您需要从C显式调用Base的构造函数:

class C : public A, public B {
public:
C(C* pParent) : Base(pParent), A(pParent), B(pParent) {}
/*... */
};

If you declare a custom constructor, the default constructor is disabled. 如果声明自定义构造函数,则会禁用默认构造函数。 In virtual inheritance you need to call the virtually inherited constructor directly because otherwise it would not know whether to initialize by A or by B. 在虚拟继承中,您需要直接调用虚拟继承的构造函数,因为否则它将不知道是由A还是由B初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM