前提条件:32位WinNT操作系统
#include <iostream>
using namespace std;
class Base
{
public:
Base(int x) : a(x)
{
}
void print()
{
cout << "base" << endl;
}
private:
int a;
};
class Derived : public Base
{
public:
Derived(int x) : Base(x-1), b(x)
{
}
void print()
{
cout << "Derived" << endl;
}
private:
int b;
};
class A
{
public:
A(int x) : a(x)
{
}
virtual void print()
{
cout << "A" << endl;
}
private:
int a;
};
class B : public A
{
public:
B(int x) : A(x-1), b(x)
{
}
virtual void print()
{
cout << "B" << endl;
}
private:
int b;
};
int main() {
Base obj1(1);
cout << "size of base = " << sizeof(obj1) << endl;
Derived obj2(2);
cout << "size of Derived = " << sizeof(obj2) << endl;
A a(1);
cout << "size of A = " << sizeof(a) << endl;
B b(2);
cout << "size of B = " << sizeof(b) << endl;
return 0;
}
- 对于Base类来说,它占用内存大小为sizeof(int),等于4,print()函数不占内存。
- 对于Derived类来说,比Base类多一个整型成员,因而多四个字节,一个是8个字节。
- 对于类A来说,由于它含有虚函数,因此占用的内存除了一个整型变量之外,还包含一个隐含的虚表指针成员,一共是8个字节。
- 对于B类来说,比A类多一个整型成员,因而多4个字节,一共是12个字节。
普通函数不占用内存,只要有虚函数,就会占用一个指针大小的内存,原因是系统多用了一个指针维护这个类的虚函数表,并且注意这个虚函数无论含有多少项都不会再影响类的大小。