c++ - protected /私有(private)继承转换

标签 c++ inheritance

我在检查继承和上/下转换时无意中遇到了这个问题。为什么不允许这样做(代码被注释以显示不允许的部分)?现在我可以猜到为什么不允许这样做了,但如果有一个真实的答案就更好了。

至于 允许的代码,我知道这是因为 (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/

相关文章:

c++ - 改进折叠功能

c++ - C++ 中高效的 Sum 和 Assignment 运算符重载

c++ - imwrite opencv文件夹中的图像序列

c++ - 如何在 C++ 中使用 if else 和类型初始化?

c# - 静态方法返回它包含类类型的对象

c++ - 为什么我应该使用 Apache C++ 标准库而不是任何其他 STL 实现以及 Boost?

java - 从基类调用重新定义的方法?

java - 使用抽象方法而不是字段

javascript - Javascript 'static' 中的简单 'base class'

c++ - 派生类中虚函数的使用