没有虚函数的类,其对象内存是怎么算的呢?以下面代码分析之。
请看下面的代码
#include <iostream> #include <string> using namespace std; class Base { }; class Base1 { int i; }; class Base2 { int fun() { return 0; } }; class Base3 { int fun() { return 0; } bool sdf() { return false; } }; class Base4 { int fun() { return i; } int i; }; int main() { size_t sizebase; Base base; sizebase = sizeof(base); cout<<sizebase<<endl; Base1 base1; sizebase = sizeof(base1); cout<<sizebase<<endl; Base2 base2; sizebase = sizeof(base2); cout<<sizebase<<endl; Base3 base3; sizebase = sizeof(base3); cout<<sizebase<<endl; Base4 base4; sizebase = sizeof(base4); cout<<sizebase<<endl; system("pause"); return 0; }
代码结果是什么呢?
1 4 1 1 4
结论:
类的实例化,所谓类的实例化就是在内存中分配一块地址,每个实例在内存中都有独一无二的地址。
1.空类也会被实例化,编译器会给空类隐含的添加一个字节,这样空类实例化之后就有了独一无二的地址了。所以空类的sizeof为1。
2.类中只有成员变量时,类的sizeof为成员变量内存对齐后的大小。
3.当类中只有非虚成员函数时,在现在大多数编译器中,类的sizeof为1,不论有多少个函数。
4.当类中没有非虚函数时,类的sizeof为内存对齐后的成员变量大小。
Ps:环境 VS 2008 SP1 + XP SP3