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

Why can't I cast super class reference to a subclass that is extending another super class as well?

本文关键字:超类 扩展 另一个 子类 转换 不能 引用 为什么      更新时间:2023-10-16

我试图理解继承中的菱形问题,我正在模拟它。这是我的文件:

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

我不应该做到这一点吗?大多数教程都说这是可能的。然而,我得到编译器错误说它是模棱两可的。有人能解释一下吗?

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