虛函數
虛函數聲明只能出現在類定義中的函數原型聲明中
不能在成員函數實現的時候運行過程中多態(tài)滿足三條件
一澄耍、賦值兼容規(guī)則
二秧耗、聲明虛函數
三、有成員函數來調用或者通過指針绸硕、引用來訪問虛函數
#include<iostream>
using namespace std;
class Vehicle {
public:
virtual void Run() const; //虛函數
virtual void Stop() const;
};
void Vehicle::Run() const {
cout<<"Vehicle Run"<<endl;
}
void Vehicle::Stop() const {
cout<<"Vehicle Stop"<<endl;
}
class Bicycle:public Vehicle {
public:
void Run() const; //覆蓋基類虛函數
void Stop() const;
};
void Bicycle::Run() const {
cout<<"Bicycle Run"<<endl;
}
void Bicycle::Stop() const {
cout<<"Bicycle Stop"<<endl;
}
class Motorcar:public Vehicle {
public:
void Run() const; //覆蓋基類虛函數
void Stop() const;
};
void Motorcar::Run() const {
cout<<"Motorcar Run"<<endl;
}
void Motorcar::Stop() const {
cout<<"Motorcar Stop"<<endl;
}
void fun(Vehicle *ptr){
ptr->Run();
ptr->Stop();
}
#include<iostream>
#include "Vehicle.h"
using namespace std;
int main(){
Vehicle V1;
Vehicle V2;
Bicycle B1;
Motorcar M1;
fun(&V1);
fun(&V2);
fun(&B1);
fun(&M1);
}