用virtual关键字声明的函数叫做虚函数。
#include <iostream.h>
class animal
{
public:
void eat()
{
cout<<"animal eat"<<endl;
}
void sleep()
{
cout<<"animal sleep"<<endl;
}
virtual void breathe()
{
cout<<"animal breathe"<<endl;
}
};
class fish:public animal
{
public:
void breathe()
{
cout<<"fish bubble"<<endl;
}
};
void fn(animal *pAn)
{
pAn->breathe();
}
void main()
{
animal *pAn;
fish fh;
pAn=&fh;
fn(pAn);
}
上面代码在派生类中重新定义了基类中的 virtual void breathe()函数,为虚函数。全局函数的参数为指向animal类的指针变量。主函数中定义了定义了一个animal类的指针,一个fish类的对象fh,将fh的地址赋给了指向animal类的指针变量pAn,然后调用fn()函数。
程序输出为 fish bubble
因为C++编译器在编译时发现animal类的breach()函数是虚函数,就会采用迟绑定技术(就是编译时不确定具体调用的函数,而是运行时根据对象的类型确定)。
C++的这种能力就叫做多态性。概括多态性就是:在基类的函数前面加上virtual,在派生类中重写该函数,运行时就会根据具体的对象来调用相应的函数。
纯虚函数:
如果将类中breach()函数定义成如下形式
virtual void breathe()=0;
breach()函数就为纯虚函数,纯虚函数指只表明而不具体实现的虚成员函数。包含纯虚成员函数的类成为抽象类,这种类不能声明对象只能作为基类为派生类服务。纯虚函数可以让类先有一个操作,而没有操作内容,在定义派生类再定义内容。在派生类中必须完全实现纯虚函数的内容。