C++ 虚拟继承

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/419943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:14:48  来源:igfitidea点击:

virtual inheritance

c++inheritancevirtual

提问by Gal Goldman

What is the meaning of "virtual" inheritance?

“虚拟”继承是什么意思?

I saw the following code, and didn't understand the meaning of the keyword virtualin the following context:

我看到以下代码,并没有理解virtual以下上下文中关键字的含义:

class A {};
class B : public virtual A;

回答by ogee

Virtual inheritance is used to solve the DDD problem (Dreadful Diamond on Derivation).

虚拟继承用于解决 DDD 问题(Dreadful Diamond on Derivation)。

Look at the following example, where you have two classes that inherit from the same base class:

看下面的例子,你有两个继承自同一个基类的类:

class Base
{

public:

 virtual void  Ambig();

};


class C : public Base
{

public:

//...

};

class D : public Base
{
public:

    //...

};


Now, you want to create a new class that inherits both from C and D classes (which both have inherited the Base::Ambig() function):

现在,您要创建一个继承 C 和 D 类的新类(它们都继承了 Base::Ambig() 函数):

class Wrong : public C, public D
{

public:

...

};

While you define the "Wrong" class above, you actually created the DDD (Diamond Derivation problem), because you can't call:

当您定义上面的“错误”类时,您实际上创建了 DDD(钻石派生问题),因为您无法调用:

Wrong wrong;
wrong.Ambig(); 

This is an ambiguous function because it's defined twice:

这是一个模棱两可的函数,因为它被定义了两次:

Wrong::C::Base::Ambig()

And:

和:

Wrong::D::Base::Ambig()

In order to prevent this kind of problem, you should use the virtual inheritance, which will know to refer to the right Ambig()function.

为了防止这种问题,你应该使用虚拟继承,它会知道引用正确的Ambig()函数。

So - define:

所以 - 定义:

class C : public virtual Base

class D : public virtual Base

class Right : public C, public D