c ++虚拟继承 [英] c++ virtual inheritance

查看:118
本文介绍了c ++虚拟继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

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
  /* ... */
};

在给定的位置,gcc抱怨它不能匹配对Base()的函数调用,构造函数。但C不是直接从Base继承,只通过A和B.那么为什么gcc在这里抱怨?

At the position given, gcc complains that it cannot match function call to Base(), i.e. the default constructor. But C doesn't inherit directly from Base, only through A and B. So why does gcc complain here?

想法?
TIA
/ Rob

Ideas? TIA /Rob

推荐答案

virtual 基类是特殊的,因为它们由最多派生类初始化,而不是从继承自虚拟基类的任何中间基类初始化。哪个潜在的多个初始化器将正确选择初始化一个基础?

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.

请注意,虚拟基本标识符允许在构造函数的初始化器列表中使用,即使它是不是所讨论的类的直接基础。

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.

这篇关于c ++虚拟继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆