说明
关于c++中类的大小的问题,首先看下面的一个例子:
#include <iostream>
using std::cout;
using std::endl;
class Father {
private:
int age;
public:
void showAge() {
cout << "Age: " << age << endl;
}
};
class Mother {
};
class Son : public Father {
};
class Sister : public Father {
private:
static int a;
};
int main() {
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of Father: " << sizeof(Father) << endl;
cout << "Size of Mother: " << sizeof(Mother) << endl;
cout << "Size of Son : " << sizeof(Son) << endl;
cout << "Size of Sister: " << sizeof(Sister) << endl;
return 0;
}
下面是执行的结果:
从上面的结果可以看出以下的几点:
1. 类中的方法并不是算在类的大小中。(见int的大小和Father的大小)
2. 空的类的大小是1个字节,而不是0。(见Mother的大小)
3. 虽然子类不能访问父类的private变量,但是在子类中也包含这个变量。(见Father和Son的大小)
4. static变量的大小不包含在类中。(见Father和Sister的大小)
以上是在没有虚函数的情况下,如果将Father中的showAge()修改成虚函数:
class Father {
private:
int age;
public:
virtual void showAge() {
cout << "Age: " << age << endl;
}
};
结果如下:
多出来的4个字节实际上是指向虚函数表的指针大小。