一个C++关于成员变量偏移地址的小Trick
今天看到一个小例子,发现了一个小trick。见代码:
#include <cstdio>
#include <cstdlib>
class base_1
{
public:
int a;
};
class base_2
{
public:
int b;
};
class base_3: public base_1, public base_2
{
public:
int c;
};
int main(int argc, char* argv[]) {
printf("&base_1::a = %p\n", &base_1::a);
printf("&base_2::b = %p\n", &base_2::b);
printf("&base_3::a = %p\n", &base_3::a);
printf("&base_3::b = %p\n", &base_3::b);
printf("&base_3::c = %p\n", &base_3::c);
base_3 t;
t.a = 1;
t.b = 2;
t.c = 3;
typedef int (base_3::*tip);
tip pm = NULL;
printf("base_3::a = %d\n", t.base_3::a);
printf("base_3::b = %d\n", t.base_3::b);
printf("base_3::c = %d\n", t.base_3::c);
pm = &base_3::a;
printf("base_3::a(%p) = %d(ptr)\n", pm, t.*pm);
pm = &base_3::b;
printf("base_3::b(%p) = %d(ptr)\n", pm, t.*pm);
pm = &base_3::c;
printf("base_3::c(%p) = %d(ptr)\n", pm, t.*pm);
return 0;
}
猜猜看这个代码输出什么? 答案是: