为什么我不能将超类引用转换为扩展另一个超类的子类?

时间:2014-03-26 00:22:11

标签: c++ inheritance multiple-inheritance

我正在尝试理解继承中的钻石问题,我正在模拟它。这就是我所拥有的:

using namespace std;

class top {
    int a;
};

class left : public top {
    int b;
};

class right : public top {
    int c;
};

class bottom : public left, public right {
    int d;
};

int main() {

    bottom* b = new bottom ();

    left* l = (left*) b;
    right* r = (right*) b;

    cout << l << " " << r << endl;
    return 0;
}

我不应该能够做到这一点吗?大多数教程都说这是可能的。但是我收到编译错误,说它不明确。有人可以在这里给出解释和一些背景吗?

1 个答案:

答案 0 :(得分:1)

您应该避免using namespace std std::leftstd::right与您自己的定义发生冲突。

有关正常工作的版本,请参阅http://ideone.com/tMa28j