为了要解决上述不能正确分辨对象类型的问题,c++提供了一种叫做多态性(polymorphism)的技术来解决问题,对于例程序1,这种能够在编译时就能够确定哪个重载的成员函数被调用的情况被称做先期联编(early binding),而在系统能够在运行时,能够根据其类型确定调用哪个重载的成员函数的能力,称为多态性,或叫滞后联编(late binding),下面我们要看的例程3,就是滞后联编,滞后联编正是解决多态问题的方法。
代码如下:
//例程3 #include <iostream> using namespace std; class Vehicle { public: Vehicle(float speed,int total) { Vehicle::speed = speed; Vehicle::total = total; } virtual void ShowMember()//虚函数 { cout<<speed<<"|"<<total<<endl; } protected: float speed; int total; }; class Car:public Vehicle { public: Car(int aird,float speed,int total):Vehicle(speed,total) { Car::aird = aird; } virtual void ShowMember()//虚函数,在派生类中,由于继承的关系,这里的virtual也可以不加 { cout<<speed<<"|"<<total<<"|"<<aird<<endl; } public: int aird; }; void test(Vehicle &temp) { temp.ShowMember(); } int main() { Vehicle a(120,4); Car b(180,110,4); test(a); test(b); cin.get(); }
多态特性的工作依赖虚函数的定义,在需要解决多态问题的重载成员函数前,加上virtual关键字,那么该成员函数就变成了虚函数,从上例代码运行的结果看,系统成功的分辨出了对象的真实类型,成功的调用了各自的重载成员函数。
多态特性让程序员省去了细节的考虑,提高了开发效率,使代码大大的简化,当然虚函数的定义也是有缺陷的,因为多态特性增加了一些数据存储和执行指令的开销,所以能不用多态最好不用。 |