首页 > C++编程 > C++空类sizeof字节数(二)

C++空类sizeof字节数(二)

下一个面试题:说明输出结果,并解释。

#include <iostream>
using namespace std;
 
class A
{
private:
	char array[0];
};
 
class B{};
 
class C : public B{};
 
int main()
{
	cout << "sizeof(A):" << sizeof(A) << endl;
	cout << "sizeof(B):" << sizeof(B) << endl;
	cout << "sizeof(C):" << sizeof(C) << endl;
 
	return 0;
}

B和C的sizeof操作返回1在上一篇文章已经说过了。至于sizeof(A)暂时不知道什么原因,输出了0,哪位朋友知道的可以解释一下。


觉得文章还不错?点击此处对作者进行打赏!


本文地址: 程序人生 >> C++空类sizeof字节数(二)
作者:代码疯子(Wins0n) 本站内容如无声明均属原创,转载请保留作者信息与原文链接,谢谢!


更多



分类: C++编程 标签: , ,
  1. 2011年8月5日23:52 | #1

    I just tried with VS2008 release, sizeof(A) is still 1, and it should be correct, otherwise how to allocate A[100], kind of conflict to standards.

    [回复]

    代码疯子 回复:

    @sali, I thought this problem sometime later and wrote a blog at http://www.programlife.net/cpp-empty-class-object-sizeof-problem.html (I’m not sure whether you can understand it, you can read it with google translate).

    Thanks for your visiting my blog :)

    [回复]

    代码疯子 回复:

    @sali, There is a warning in VS2005:
    1>c:\users\Administrator\documents\visual studio 2005\projects\testest\testest\testest.cpp(8) : warning C4200: nonstandard extension used : zero-sized array in struct/union
    1> Cannot generate copy-ctor or copy-assignment operator when UDT contains a zero-sized array

    [回复]

  1. 本文目前尚无任何 trackbacks 和 pingbacks.