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

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

问题描述

我想知道一个虚拟基类是什么意思。

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

让我举个例子: p>

Let me show an example:

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 {};

上述类层次结构产生dreaded diamond,如下所示:

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

  A
 / \
B   C
 \ /
  D

D的实例将由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

希望有助于作为小型摘要。有关详情,请阅读这里也是一个很好的例子。

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

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

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