铸造从衍生到基础,模棱两可

时间:2013-02-27 12:21:38

标签: inheritance multiple-inheritance dynamic-cast

假设我们有

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:错误:'派生'是'底部'的模糊基础

int main()
{
}

那么,为什么在

的情况下编译代码
Base* bptr = new Bottom; 

而不是

Bottom* bptr = new Bottom; 

1 个答案:

答案 0 :(得分:-1)

你已经问了同一个问题。所以我会回答简短的问题: 这是钻石问题。 在这种情况下,你的类型Base的指针,派生,Base类只知道在这种情况下唯一的子类。 但是从Bottom类型的对象来看,它的含糊不清,你想要使用派生类,它是Derived_left或Derived_Right的父类。

相关问题