虚函数的定义要遵循以下重要规则:
1.如果虚函数在基类与派生类中出现,仅仅是名字相同,而形式参数不同,或者是返回类型不同,那么即使加上了virtual关键字,也是不会进行滞后联编的。
2.只有类的成员函数才能说明为虚函数,因为虚函数仅适合用与有继承关系的类对象,所以普通函数不能说明为虚函数。
3.静态成员函数不能是虚函数,因为静态成员函数的特点是不受限制于某个对象。
4.内联(inline)函数不能是虚函数,因为内联函数不能在运行中动态确定位置。即使虚函数在类的内部定义定义,但是在编译的时候系统仍然将它看做是非内联的。
5.构造函数不能是虚函数,因为构造的时候,对象还是一片位定型的空间,只有构造完成后,对象才是具体类的实例。
6.析构函数可以是虚函数,而且通常声名为虚函数。
在编译时就能够确定哪个重载的成员函数被调用的情况被称做先期联编(early binding),而在系统能够在运行时,能够根据其类型确定调用哪个重载的成员函数的能力,称为多态性,或叫滞后联编(late binding)
//例程3
#include
using namespace std;
class Vehicle
{
public:
Vehicle(float speed,int total)
{
Vehicle::speed = speed;
Vehicle::total = total;
}
virtual void ShowMember()//虚函数
{
cout< } 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< } 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(); } 运行结果:120|4 110|4|180 //例程2 #include using namespace std; class Vehicle { public: Vehicle(float speed,int total) { Vehicle::speed=speed; Vehicle::total=total; } void ShowMember() { cout< } protected: float speed; int total; }; class Car:public Vehicle { public: Car(int aird,float speed,int total):Vehicle(speed,total) { Car::aird=aird; } void ShowMember() { cout< } protected: int aird; }; void test(Vehicle &temp) { temp.ShowMember(); } void main() { Vehicle a(120,4); Car b(180,110,4); test(a); test(b); cin.get(); } 运行结果:120|4 110|4 虚继承是为了在多继承的时候避免引发歧义, 比如类A有个就是a,B继承了A,C也继承了A,当D多继承B,C时,就会有歧义产生了,所以要使用虚拟继承避免重复拷贝。