【问题标题】:Casating from Derived to Base, ambiguouty从 Derived 转换为 Base,歧义
【发布时间】:2013-02-27 12:21:38
【问题描述】:

假设我们有

class Base
{
public:
    virtual void foo(){}
};

class Derived: public virtual Base
{};

class Derived_Left: public Derived
{};

class Derived_Right: public Derived
{};

class Bottom: public Derived_Left, public Derived_Right
{};

//让我们讨论案例

//案例一:

void foo()
{
    Base *bptr = new Bottom;
    Derived *dPtr = dynamic_cast<Derived*>(bptr);//dptr == 0
}

//案例2:

void goo()
{
    Bottom *bptr = new Bottom;
    Derived *ddtr = dynamic_cast<Derived*>(bptr); // ERROR
}

//main.cpp: 在函数'void goo()'中:

//main.cpp:36:49: 错误:‘Derived’是‘Bottom’的模糊基数

int main()
{
}

那么,为什么要在以下情况下编译代码

Base* bptr = new Bottom; 

而不是

Bottom* bptr = new Bottom; 

【问题讨论】:

  • 首先我想提一下我第一次在ubuntu g++下编译它。它给了我这个错误。但是在家里我试图在 windows/visual stuio 2012 下编译它,它只给了我一个警告警告 C4540: dynamic_cast used to convert to inaccessible or ambiguous base;运行时测试将失败('Bottom *' to 'Derived *')

标签: inheritance multiple-inheritance dynamic-cast


【解决方案1】:

您已经问过同样的问题。所以我会简短地回答: 是钻石问题。 在这种情况下,您将 Type Base 的指针转换为派生的,Base 类只知道在这种情况下唯一的子类。 但是从 Bottom 类型的对象的角度来看,它是模棱两可的,您希望使用派生类,它是 Derived_left 或 Derived_Right 的父类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2014-03-27
    • 2017-08-06
    • 2019-02-06
    相关资源
    最近更新 更多