在 C++ 中,什么是虚拟基类? [英] In C++, what is a virtual base class?

查看:44
本文介绍了在 C++ 中,什么是虚拟基类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道虚拟基类"是什么以及它的含义.

I want to know what a "virtual base class" is and what it means.

让我举个例子:

class Foo
{
public:
    void DoSomething() { /* ... */ }
};

class Bar : public virtual Foo
{
public:
    void DoSpecific() { /* ... */ }
};

推荐答案

在虚拟继承中使用的虚拟基类是一种在使用多重继承时防止给定类的多个实例"出现在继承层次结构中的方法.

Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance.

考虑以下场景:

class A { public: void Foo() {} };
class B : public A {};
class C : public A {};
class D : public B, public C {};

上面的类层次结构导致可怕的菱形"看起来像这样:

The above class hierarchy results in the "dreaded diamond" which looks like this:

  A
 / 
B   C
  /
  D

D 的一个实例将由 B 组成,B 包括 A,C 也包括 A.所以你有两个 A 的实例"(为了更好的表达).

An instance of D will be made up of B, which includes A, and C which also includes A. So you have two "instances" (for want of a better expression) of A.

当您遇到这种情况时,您就有可能产生歧义.当你这样做时会发生什么:

When you have this scenario, you have the possibility of ambiguity. What happens when you do this:

D d;
d.Foo(); // is this B's Foo() or C's Foo() ??

虚拟继承就是为了解决这个问题.当您在继承类时指定 virtual 时,您是在告诉编译器您只需要一个实例.

Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance.

class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};

这意味着层次结构中只包含 A 的一个实例".因此

This means that there is only one "instance" of A included in the hierarchy. Hence

D d;
d.Foo(); // no longer ambiguous

这是一个小总结.如需更多信息,请阅读this这个.此处也提供了一个很好的示例.

This is a mini summary. For more information, have a read of this and this. A good example is also available here.

这篇关于在 C++ 中,什么是虚拟基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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