通过地址偏移访问和修改类的成员变量

假设有如下类:

class Test 
{
public:
	int age { 100 };
}

有下列两种方式访问和修改age字段。

方法一: 通过原始的地址偏移方式

Test test;
// 还可以这样计算offset: 
// int Test::* age_p = &Test::age; 
// int offset = *(int*)&age_p;
int offset = (size_t)&(test.age) - (size_t)&test;

// 修改
*(int*)((char*)&test+offset) = 200;

// 访问
cout << *(int*)((char*)&test+offset) << endl;

方法二: 通过成员指针

Test test;

int Test::* age_p = &Test::age; 
// 修改
test.*age_p = 200;

// 访问
cout << test.*age_p << endl;
posted @ 2022-12-16 12:33  GameSprite  阅读(42)  评论(0编辑  收藏  举报