此代码是否会导致未定义的行为?或者我可以遇到这个问题吗?(复制没有函数的完整类,只使用带有公共修饰符的变量并修改私有成员抛出这个指针)示例:
#include <iostream>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point(int x, int y) {
this->x = x;
this->y = y;
}
void Print() {
cout << "(" << x << ", " << y << ")" << endl;
}
};
struct PointHack {
int x;
int y;
};
int main() {
Point a(4, 5);
a.Print();
((PointHack *) (&a))->x = 1;
((PointHack *) (&a))->y = 2;
a.Print();
return 0;
}
输出:
(4, 5)
(1, 2)
(当然是原始会员订单)