1、虚函数的作用
虚函数通过动态联编技术,使程序运行时选择正确的虚方法。使用虚函数,会根据对象的类型来调用函数,而不是根据指针类型。
#include<iostream>
using namespace std;
class A{
public:
A(){}
virtual void show(){ cout << "this is A show" << endl;}
~A(){}
};
class B: public A {
public:
B(){}
void show(){ cout << "this is B show" << endl;}
~B(){}
};
class C: public A{
public:
C(){}
void show(){ cout << "this is C show" << endl;}
~C(){}
};
int main(){
B b;
C c;
A* a;
a = &b;
a -> show();
a = &c;
a -> show();
}
输出结果为:
this is B show
this is C show
虚函数反映了多态的思想,用基类指针根据指向的对象,调用不同的对象所属函数。
2、虚函数的工作原理
通常,编译器处理虚函数方法是,给每个对象添加一个隐藏成员。隐藏成员中保存了一个指向函数地址数组的指针。这个数组叫做虚函数表。虚函数表保存了为类对象进行声明的虚函数地址。基类中包含一个指向虚函数表的指针,虚函数表保存了所有虚函数的地址