例子,求下面的程序输出。
/home/a/j/nomad2:cat ch3.CPP
#include <iostream>
using namespace std;
class X
{
};
class Y : public virtual X
{
/*
public:
char c;
*/
};
class Z : public virtual X
{
/*
public:
char d;
*/
};
class A : public Y, public Z
{
};
int main()
{
cout << sizeof(X) << endl;
cout << sizeof(Y) << endl;
cout << sizeof(Z) << endl;
cout << sizeof(A) << endl;
}
输出如下:
/home/a/j/nomad2:uname -a Linux ubuntu 2.6.24-22-generic #1 SMP Mon Nov 24 19:35:06 UTC 2008 x86_64 GNU/Linux /home/a/j/nomad2:./a.out 1 8 8 16
|
Each class object, then, is exactly the size necessary to contain the nonstatic data members of its class. This size may at times surprise you as being larger than necessary, as it did my correspondent from France. This girth comes about
in two ways: |
C++多重继承内存布局
本文通过一个C++示例程序展示了在使用多重继承时,不同类对象的内存占用情况。特别关注了虚拟继承对内存布局的影响,并解释了类大小可能大于预期的原因,包括编译器为支持虚拟继承而添加的数据成员以及对数据成员的对齐要求。

被折叠的 条评论
为什么被折叠?



