虚函数和多态

来源:互联网 发布:编程语言 知乎 编辑:程序博客网 时间:2024/06/15 12:08
#pragma once//普通飞机class Plane{public:virtual void fly();virtual void land();};


#include "Plane.h"#include <iostream>using namespace std;void Plane::fly(){cout << "起飞" << endl;}void Plane::land(){cout << "着陆" << endl;}

#pragma once#include "Plane.h"//直升飞机class Jet : public Plane{virtual void fly();virtual void land();};

#include "Jet.h"#include <iostream>using namespace std;void Jet::fly(){cout << "直升飞机在原地起飞..." << endl;}void Jet::land(){cout << "直升飞机降落在女神的屋顶..." << endl;}

/*//虚函数//多态(程序的扩展性)//动态多态:程序运行过程中,觉得哪一个函数被调用(重写)//静态多态:重载//发生动态的条件://1.继承//2.父类的引用或者指针指向子类的对象//3.函数的重写#include "Plane.h"#include "Jet.h"#include "Copter.h"//业务函数void bizPlay(Plane& p){p.fly();p.land();}void main(){Plane p1;bizPlay(p1);//直升飞机Jet p2;bizPlay(p2);Copter p3;bizPlay(p3);system("pause");}*/


原创粉丝点击