下面的程序可以正常运行,即使类 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;
}
reinterpret_cast
基本上意味着:闭嘴编译器,我知道自己在做什么,只需将此类型视为另一种类型处理,我会接受后果。在大多数情况下,使用reinterpret_cast
可能是一个错误。有一些情况下,您必须强制编译器并颠覆类型系统,但这些情况很少见。而且,您可以以明确定义的方式执行此操作的情况更少。重新解释转换除了“您可以将 foo 转换为 bar(如果 bar 足够大),然后可以将 bar 转换回 foo”之外,并没有给您太多保证。 - Jesper Juhl