内存偏移
1 #include "stdafx.h" 2 3 class A 4 { 5 public: 6 A(){m_a = 1; m_b = 2;} 7 void fun(){printf("%d %d\n", m_a, m_b);} 8 private: 9 int m_a; 10 int m_b; 11 }; 12 13 class C 14 { 15 public: 16 C(){m_c = 3;} 17 void fun(){printf("%d\n", m_c);} 18 private: 19 int m_c; 20 }; 21 22 int _tmain(int argc, _TCHAR* argv[]) 23 { 24 A a; 25 C c; 26 printf("0x%p\n", &a); 27 printf("0x%p\n", &c); 28 29 C *pc = (C *)&a; 30 printf("0x%p\n", pc); 31 32 pc->fun(); 33 34 return 0; 35 }
输出:
0x0018FF24
0x0018FF18
0x0018FF24
1
分析:
C *pc = (C *)&a;
强制用C的内存模型解释a的地址指向的内容, pc->fun()调用C::fun()打印m_c时,编译器对m_c的认识就是m_c是距离对象首地址偏移量为0的数据。