简体   繁体   English

C ++中的Diamond继承代码无法按预期工作

[英]Diamond inheritance code in C++ not working as expected

I'm trying to understand the solution to the diamond problem (multiple inheritance) in C++. 我试图了解C ++中钻石问题(多重继承)的解决方案。

I've written this code to better understand the solution but it doesn't behave as expected. 我编写了这段代码是为了更好地理解该解决方案,但它的行为不符合预期。

#include <stdio.h>

class A
{
public:
    void Print()
    {
        printf("A\n");
    }
};

class B : virtual public A
{
public:
    void Print()
    {
        printf("B\n");
    }
};

class C : virtual public A
{
public:
    void Print()
    {
        printf("C\n");
    }
};

class D : public B, public C
{
};

int main()
{
    D d;
    d.Print();
}

Visual studio 2008 express edition yells out : error C2385: ambiguous access of 'Print' 1> could be the 'Print' in base 'B' 1> or could be the 'Print' in base 'C' error C3861: 'Print': identifier not found Visual Studio 2008速成版大喊:错误C2385:对“打印” 1>的模糊访问可能是基本“ B”中的“打印” 1>或可能是基本“ C”中的“打印”错误C3861:“打印” :找不到标识符

Can anyone please tell me what I'm missing here? 谁能告诉我我在这里想念的吗?

Which version of Print() should d.Print() call? d.Print()应该调用哪个版本的Print() There are two choices. 有两种选择。 You can choose, though: 您可以选择:

d.A::Print(); // this one isn't part of the overload set search without qualification
d.B::Print();
d.C::Print();

Note that making A::Print() a virtual function won't help as there is no unique final overriding function. 请注意,将A::Print()设为virtual函数将无济于事,因为没有唯一的最终覆盖函数。 You'd need to explicitly override Print() in D . 您需要显式重写D Print()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM