#include <iostream>
using namespace std;
class test {
public:
void show() {
cout << y << '\n';
}
public:
int x = 10;
int y = 20;
};
#define offset_(x, yy) ((size_t)&((x *)nullptr)->y)
int main() {
test a;
int y = *(int *)((uint64_t)&a + offset_(test, y));
cout << y << '\n';
a.show();
return 0;
}
offset的宏实现
OFFSET_OF(TYPE, FIELD) ((size_t)&((TYPE*)nullptr)->FIELD)
虚继承时offset会出现负的情况