#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.