美文网首页
C++|多态与虚函数

C++|多态与虚函数

作者: 绍重先 | 来源:发表于2017-11-30 20:31 被阅读0次

虚函数

  • 虚函数声明只能出现在类定义中的函数原型声明中
    不能在成员函数实现的时候

  • 运行过程中多态满足三条件
    一、赋值兼容规则
    二、声明虚函数
    三、有成员函数来调用或者通过指针、引用来访问虚函数

#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); 
}
image.png

相关文章

网友评论

      本文标题:C++|多态与虚函数

      本文链接:https://www.haomeiwen.com/subject/yisbbxtx.html