直接看代码:
#include <stdlib.h>
#include <stdio.h>
class CEmpty
{
public:
CEmpty()
{
}
~CEmpty()
{
}
};
int main()
{
CEmpty emptyClass;
printf("sizeof CEmpty is: %lu\n", sizeof(emptyClass));
return 0;
}
1,首先什么样的才是空类呢?
它是一个不包含任何数据成员的类(例如int a、float b、char c和string d等)。然而,空类可能包含成员函数。
2,为什么空类的大小是 1 byte 呢?
简单地说,类只有在实例化的时候才会分配内存空间,即定义变量时(栈上定义或堆上定义),那分配内存空间肯定要有大小,而空类的大小是由编译器定的,这样一个类定义多个对象时,能保证每个对象的地址都是唯一的。如:
#include <stdlib.h>
#include <stdio.h>
class CEmpty
{
public:
CEmpty()
{
}
~CEmpty()
{
}
};
int main()
{
printf("sizeof CEmpty is: %lu\n", sizeof(CEmpty));
CEmpty emptyClass1, emptyClass2;
if(&emptyClass1 == &emptyClass2)
{
printf("two object address are same\n");
}
else
{
printf("two object address are not same\n");
}
return 0;
}
看下面的代码,一个派生类继承于一个空基类,其大小是多少呢?
#include <stdlib.h>
#include <stdio.h>
class CEmpty
{
public:
CEmpty()
{
}
~CEmpty()
{
}
};
class Derived: public CEmpty
{
private:
int mValue;
};
int main()
{
printf("sizeof CEmpty is: %lu\n", sizeof(CEmpty));
CEmpty emptyClass1, emptyClass2;
if(&emptyClass1 == &emptyClass2)
{
printf("two object address are same\n");
}
else
{
printf("two object address are not same\n");
}
Derived derive;
printf("sizeof derive is: %lu\n", sizeof(derive));
return 0;
}
这里有个有趣的规则 :
Note: The output is not greater than 4. There is an interesting rule that says that an empty base class need not be represented by a separate byte. So compilers are free to make optimization in case of empty base classes.
我们知道类的大小是不包括成员函数及static成员数据的,为什么呢?我想应该是:成员函数和static成员是属于类层面的,它不属于对象,那对象是什么呢?对象就是定义的变量,而非static成员数据才是每个对象的东西,它们是对象的一部分。可能对初学者不好理解,下面一个例子也许可以帮助理解:
#include <stdlib.h>
#include <stdio.h>
class CEmpty
{
public:
CEmpty()
{
}
~CEmpty()
{
}
void doNothing()
{
printf("nothing to do\n");
}
static int mValue;
};
int main()
{
printf("sizeof CEmpty is: %lu\n", sizeof(CEmpty));
CEmpty *test = NULL;
test->doNothing();
return 0;
}
定义了一个 CEmpty 的指针且赋值为NULL,第一眼看上去觉得 test->doNothing(); 肯定有问题,NULL 指针怎么能这样用呢?而结果呢?
为什么不会崩溃?
第一是函数并不属于对象,不一定要有效的对象才能调用;第二是this指针,因为这个函数里没有引用到成员数据,假如有引用成员数据必定崩溃的。可以用 objdump 查看 a.out, 函数其实是存放在文本区(.text)的,它不是对象的一部分,而对象是通过函数的第一个参数传递进来的。
注意:然而在 c 语言中,空的结构体的大小是 0,目前找到的原因是:在C语言中引入结构时,当时还没有对象的概念。因此,根据C标准,决定将空结构的大小保持为 0。