首页 > 其他分享 >通过地址偏移访问和修改类的成员变量

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

时间:2022-12-16 12:46:05浏览次数:36  
标签:变量 访问 int age test 地址 偏移 offset Test

假设有如下类:

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;

标签:变量,访问,int,age,test,地址,偏移,offset,Test
From: https://www.cnblogs.com/pixs-union/p/16987015.html

相关文章