【发布时间】:2018-12-11 14:45:36
【问题描述】:
我在应用继承时正在阅读有关访问说明符的信息,并且我知道在 private inheritance 中,我们无法使用指针/引用从派生类转换为基类。
但是当我使用reinterpret_cast 时,它起作用了。下面是我的测试代码:
class base {
int _a;
public:
base(int a): _a(a) {}
base(): _a(0) {}
};
class derived : private base
{
public:
derived(int b):base(b) {};
};
int main() {
derived b(25);
base &a = static_cast<base&>(b);//this line will generate a compile error
base &c = reinterpret_cast<base&>(b); //here it works
}
所以我的问题甚至是私有继承,为什么基类会使用retinterpret_cast 公开?
谢谢!
//EDIT 2
class base {
int _a;
public:
base(int a): _a(a) {}
base(): _a(100) {}
~base() { std::cout << "deleting base" << _a << "\n"; }
};
class derived : private base
{
public:
virtual ~derived() = default;
derived(int b):base(b) {};
};
int main() {
derived b(25);
base &c = reinterpret_cast<base&>(b);
}
//OutPut : Deleting 25
【问题讨论】:
-
您不应该使用
static_cast或reinterpret_cast进行向上转换或向下转换。请改用dynamic_cast -
是的,你是对的,我必须使用需要多态类的dynamic_cst,但它是用于测试:)
-
reinterpret_cast与旧的 C 风格转换非常相似,因为它基本上告诉编译器“我知道我在做什么,不要打扰我”。如果您实际上不知道自己在做什么,或者犯了任何错误,编译器仍然不会打扰您,并且会很乐意借给您一把枪,这样您就可以朝自己的脚开枪了。 -
在实践中和简单的继承情况下,
static_cast、C 风格的强制转换、reinterpret_cast都被编译为无操作(即不生成代码,如标识函数) .但是,dynamic_cast有运行时成本(并且需要一些生成的代码) -
“所以我的问题甚至是私有继承,为什么基类会使用 retinterpret_cast 公开” - 不是。即使
derived没有从base继承根本,reinterpret_cast仍然可以编译。
标签: c++ casting reinterpret-cast