读书人

C++中的sizeof难倒了!解决思路

发布时间: 2012-04-19 14:36:43 作者: rapoo

C++中的sizeof难倒了!!
对于下面的代码,
class X
{
public:
static int g_iMem;
};

class Y
{
public:
virtual void Feature();
char m_c1;
};

class Z : public Y
{
public:
char m_c2;
X x;
int m_i1;
};
假设环境是一个32位系统,则运行时,sizeof(Z)的值是(C)
(A)8
(B)12
(C)16
—)20


问:答案为什么C啊!就各位帮忙分析一下,详细点最好。

[解决办法]

C/C++ code
#include <iostream>using namespace std;class X{public:    static int g_iMem;       // 因为是static,所以它是类级别的,而非对象级别的,即};                               // 类X的所有的对象都会共享g_iMem。理论上sizeof(X)是0,                                 // 但大多数编译器都会给1byte的占位符,因此sizeof(X) = 1byteclass Y{public:    virtual void Feature();        // 4bytes    char m_c1;                    // 4bytes};class Z : public Y{public:    char m_c2;                    // 4bytes    X x;                        // 0byte    int m_i1;                    // 4bytes};int main(int argc, char *argv[]){    cout << sizeof(X) << endl;    // 1byte    cout << sizeof(Y) << endl;    // 8bytes    cout << sizeof(Z) << endl;    // 16bytes    return 0;}
[解决办法]
探讨

这个题是脑残

读书人网 >C++

热点推荐