C++中类的数据成员在内存中时如何分布的,有继承,虚拟继承等情况下又是怎么分布的?在VS编译器中可以查看。
源代码如下:
#include<iostream>
using namespace std;
class CFurniture
{
public:
CFurniture(){
m_nPrice = 0;
}
~CFurniture(){
printf("virtual ~CFurniture()\r\n");
}
virtual int GetPrice(){
return m_nPrice;
}
protected:
int m_nPrice;
};
class Csofa:virtual public CFurniture
{
public:
Csofa(){
m_nColor = 1;
m_nColor = 2;
}
~Csofa(){
printf("virtual ~Csofa()\r\n");
}
virtual int GetColor(){
return m_nColor;
}
virtual int SitDown(){
return printf("Sit Down and rest your legs\r\n");
}
protected:
int m_nColor;
};
class CBed : virtual public CFurniture
{
public:
CBed(){
m_nPrice = 3;
m_nLength = 4;
m_nWidth = 5;
}
~CBed(){
printf("virtual ~CBed()\r\n");
}
virtual int GetArea(){
return m_nLength*m_nWidth;
}
virtual int Sleep(){
return printf("go to sleep\r\n");
}
protected:
int m_nLength;
int m_nWidth;
};
class CSofaBed : public Csofa,public CBed
{
public:
CSofaBed(){
m_nHeight = 6;
}
~CSofaBed(){
printf("virtual ~CSoftBed()\r\n");
}
virtual int SitDown(){
return printf("Sir Down on the sofa bed\r\n");
}
virtual int Sleep(){
return printf("go to sleep on the sofa bed\r\n");
}
virtual int GetHeight(){
return m_nHeight;
}
protected:
int m_nHeight;
};
void main(){
CSofaBed SofaBed;
CFurniture* pFunniture = &SofaBed;
Csofa* pSofa = &SofaBed;
CBed* pBed = &SofaBed;
}
1、打开 Visual Studio Tools 中的 VS2013 开发人员命令提示
2、切换到.cpp文件所在的目录
3、输入命令:cl -d1reportSingleClassLayout[类名] [文件名].cpp
4、也可以在编辑界面中,右击[文件名].cpp->属性–>配置属性–>C/C+±->命令行:其他选项,添加:/d1reportSingleClassLayout[类名] [文件名].cpp
5、编译,会在输出栏中显示上述信息。
5、用gcc的-fdump-class-hierarchy 参数把内存布局给打印出来
-fsyntax-only 只是检查语法。
gcc -fdump-class-hierarchy -fsyntax-only CppTest.cpp
结果会在目录下生成一个CppTest.cpp.t01.class的文本文件。