Empty Classes

王朝other·作者佚名  2006-01-10
宽屏版  字体: |||超大  

#include <iostream>

#include <cstdlib>

//定义一个空类

class A {};

using namespace std;

int main(int argc, char* argv[])

{

// A is emptyclass

A* p1 = new A;

A* p2 = new A;

cout << "sizeof(A) = " << sizeof(A) << " or " << sizeof(*p1) << endl;

cout << "address p1 = " << p1 << endl;

cout << "address p2 = " << p2 << endl;

//我机器上的结果

//sizeof(A) = 1

//address p1 = 00372AD0 //address p2 = 00372B08 //p1 != p2

#endif

return 0;

}

////以下资料摘自 www.glenmccl.com

In C, an empty struct like:

struct A {};

is invalid, whereas in C++ usage like:

struct A {};

or:

class B {};

is perfectly legal. This type of construct is useful when developing a skeleton or placeholder for a class.

An empty class has size greater than zero. Two class objects of empty classes will have distinct addresses,

There are still one or two C++ compilers that generate C code as their "assembly" language. To handle an empty class, they will generate a dummy member, so for example:

class A {};

becomes:

struct A {

char __dummy;

};

in the C output.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有