在程序员面试宝典上有这么一道题:
#include <string.h>
#include <iostream.h>
#include <stdio.h>
class A
{
public:
A(){m_a = 1; m_b = 2;}
~A(){};
void fun(){printf("%d%d",m_a,m_b);}
public:
int m_a;
int m_b;
};
class B
{
public:
B(){m_c = 3;}
~B();
void fun(){printf("%d",m_c);}
public:
int m_c;
};
int tmain(void)
{
A a;
B *pb = (B*)(&a);
cout << &a << endl; //0x22ff58
cout << &(a.m_a) << endl; //print the address of the a.m_a 0x22ff58
printf("%p\n",&A::m_a); //print the offset from m_a to the beginning A object
//address 00000000
printf("%p\n",&A::m_b); //print the offset from m_a to the beginning A object
//address 00000004
printf("%p\n",&B::m_cn); //print the offset from m_c to the beginning B object
//address 00000000
system("PAUSE");
return 0;
}
我的问题是:
(1)为什么内存的偏移是从成员变量开始?成员函数放在哪了呢?比如printf("%p\n",&A::fun);输出的是个
很大的偏移量,为什么?
(2)类在内存中具体是怎么保存的? |