0

假设我们有

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

//让我们讨论案例

//情况1:

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' 的模糊基数</p>

int main()
{
}

那么,为什么要编译代码以防万一

Base* bptr = new Bottom; 

而不是在

Bottom* bptr = new Bottom; 
4

1 回答 1

-1

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

于 2013-08-20T09:05:04.873 回答