我在检查继承和上/下转换时无意中遇到了这个问题。为什么不允许这样做(代码被注释以显示不允许的部分)?现在我可以猜到为什么不允许这样做了,但如果有一个真实的答案就更好了。
至于 允许的代码,我知道这是因为 (Base*) 是 C 风格的转换,本质上是 reinterpret_cast 在 C++ 中,这反过来意味着在这种情况下它将导致未定义的行为。如果我错了,请纠正我。
class Base
{
};
class Derived : public Base
{
};
class DerivedProt : protected Base
{
};
class DerivedPriv : private Base
{
};
int main()
{
Base* a = new Derived();
Base* b = new DerivedProt(); // Not allowed
Base* c = new DerivedPriv(); // Not allowed
Base* d = (Base*) new DerivedProt(); // Allowed but undefined behavior...?
Base* e = (Base*) new DerivedPriv(); // Allowed but undefined behavior...?
}
最佳答案
标准明确规定 C 风格的转换可以执行此转换。这是 C 风格类型转换可以但 C++ 类型转换无法做到的唯一类型转换。据我所知,结果并非不确定;这是任何其他 Actor 都不允许的。
关于c++ - protected /私有(private)继承转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5372070/