【发布时间】:2019-11-15 10:54:36
【问题描述】:
即使B 类分配的内存不足以容纳A 类的所有成员,以下程序也可以正常运行。
// CPP code to illustrate the pointer reinterpret
#include <iostream>
using namespace std;
class A {
public:
void fun_a()
{
cout << " In class A\n";
}
int Val;
int Res;
};
class B {
};
int main()
{
// creating object of class B
B* x = new B();
A* new_a = reinterpret_cast<A*>(x);
// accessing the function of class A
new_a->fun_a();
new_a->Val = 10;
new_a->Res = 20;
cout << new_a->Val;
cout << new_a->Res;
return 0;
}
【问题讨论】:
-
未定义行为包括看似有效。仅供参考:en.cppreference.com/w/cpp/language/ub
-
reinterpret_cast基本上是指;只是闭嘴编译器,我知道我在做什么,只要把这种类型当作另一种类型,我会接受后果。在大多数 情况下,使用reinterpret_cast可能是一个错误。在某些情况下,您必须像这样强制编译器并颠覆类型系统,但它们很少见。你可以以明确的方式做到这一点的情况更少。除了“您可以将 foo 转换为 bar - 如果 bar 足够大 - 然后您可以将 bar 转换回 foo”之外,重新解释转换并没有给您很多保证。 -
允许
reinterpret_cast的情况相当有限(参见here)。只有一次我遇到了一个我认为我需要它的情况,结果证明我错了(无论是在我不需要它的意义上,还是在我使用它的意义上它是不允许的)
标签: c++ operator-keyword reinterpret-cast