以下程序运行没有任何问题,即使类 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;
}
最佳答案
通过指向 T
的指针进行间接定向,该指针不指向类型 T
(或兼容类型)的对象,这会导致未定义的行为。
The following program runs without any issue,
程序似乎可以正常运行是未定义行为的一个例子。
关于c++ - 了解 reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56892327/