一个类中若有虚函数,(不论是自己的虚函数,还是继承而来的),那么类中就有一个成员变量:虚函数指针。虚函数指针占4字节
直接看例子:
class base1{
private:int a;
public:virtual void fun1(){}virtual void fun2(){}
};class base2{
public:virtual void fun1(){}virtual void fun2(){}
};int main(){cout << sizeof(base1) << endl; //8cout << sizeof(base2) << endl; //4return 0;
}
如果子类继承基类,子类会继承虚函数表,不管子类有没有对虚函数重写,子类都会有虚函数指针:
class base1{
public:virtual void fun1(){}virtual void fun2(){}
};class derive1 :public base1{
public:virtual void fun1(){}virtual void fun2(){}
};class derive3 :public base1{
public:void fun6(){}void fun7(){}
};int main(){cout << sizeof(derive1) << endl; //4cout << sizeof(derive3) << endl; //4return 0;
}
如果一个子类继承自2个基类,那么子类有2个虚函数指针,所以sizeof大小为 8:
class base1{
public:virtual void fun1(){}virtual void fun2(){}
};class base2{
public:virtual void fun3(){}virtual void fun4(){}
};class derive2 :public base1,public base2{
public:virtual void fun1(){}virtual void fun2(){}virtual void fun3(){}virtual void fun4(){}
};int main(){cout << sizeof(derive2) << endl; //8return 0;
}
如果基类没有虚函数,子类继承基类后把其中一个函数设为虚函数,则基类没有虚表指针,子类有虚表指针:
class base{
private:int a; //整型4字节
public:void fun1(){}
};class derive :public base{
public:virtual void fun1(){}
};int main(){derive d1;cout << sizeof(base) << endl; //4字节,整型大小cout << sizeof(d1) << endl; //8字节,整型+虚表指针return 0;
}