<TABLE style="TABLE-LAYOUT: fixed">
#include <iostream>
using std::cout;
using std::endl;
class Base
{
public: //为了便于取地址
int m_data1;
int m_data2;
int m_data3;
public:
void mem_fun1();
void mem_fun2();
//注意虽然后面没用到这些虚函数 ,但是要使程序可以编译通过
//需要实现他们,因为建立vtable会出错
virtual void vir_fun1(){}
virtual void vir_fun2(){}
};
class Derive:public Base
{
public://为了便于取地址
int m_data1;
int m_data3;
int m_data4;
public:
void mem_fun1();
virtual void vir_fun2(){}
};
int main()
{
cout<<”sizeof(Base)=> “<<sizeof(Base)<<endl;
cout<<”sizeof(Derive)=> “<<sizeof(Derive)<<endl;
Base b;
Derive d;
cout<<”Address of b=> “<<&b<<endl;
cout<<”Address of b.m_data1=> “<<&(b.m_data1)<<endl;
cout<<”Address of b.m_data2=> “<<&(b.m_data2)<<endl;
cout<<”Address of b.m_data3=> “<<&(b.m_data3)<<endl;
cout<<”Address of d=> “<<&d<<endl;
cout<<”Address of d.m_data1=> “<<&(d.m_data1)<<endl;
cout<<”Address of d.Base::m_data2=> “<<&(d.Base::m_data2)<<endl;
cout<<”Address of d.Base::m_data3=> “<<&(d.Base::m_data3)<<endl;
cout<<”Address of d.m_data3=>”<<&(d.m_data3)<<endl;
cout<<”Address of d.m_data4=>”<<&(d.m_data4)<<endl;
system(“pause”);
return 0;
}
运行结果如图:
基类的大小为16是因为,三个int变量加上一个vptr,对应的Derive的大小就是在此基础上加三个int的大小,各数据成员的地址很清晰,也可以反映对象在内存中的存放情况。
下面两幅图是对象的内存模拟表示,看图应该就很清楚了: