C++虚继承

c++ virtual inheritance(C++虚继承)
本文介绍了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/罗布

推荐答案

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++虚继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Prevent class inheritance in C++(防止 C++ 中的类继承)
Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
C++ cast to derived class(C++ 转换为派生类)
C++ virtual function return type(C++虚函数返回类型)
Is there any real risk to deriving from the C++ STL containers?(从 C++ STL 容器派生是否有任何真正的风险?)