虚函数
虚函数声明只能出现在类定义中的函数原型声明中
不能在成员函数实现的时候运行过程中多态满足三条件
一、赋值兼容规则
二、声明虚函数
三、有成员函数来调用或者通过指针、引用来访问虚函数
#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);
}