《我的第一本C++书》--陈良乔 虚函数
作者:互联网
#include "pch.h"
#include <iostream>
using namespace std;
/***************虚函数*************/
class Human {
public:
virtual void BuyTicket() {
cout << "买票。" << endl;
}
};
class Teacher :public Human {
virtual void BuyTicket() {
cout << "老师买票。" << endl;
}
};
class Student :public Human {
virtual void BuyTicket() {
cout << "学生刷卡。" << endl;
}
};
int main()
{
/*
虚函数的作用:
当定义一个基类指针对象来保存派生类,
调用基类和派生类重载的同名函数时,
可以根据不同的派生类对象调用各自的重载函数,
而不是永远调用基类的函数
*/
Human* human=new Human();
human->BuyTicket();
delete human;
//上来一位老师
human = new Teacher;
human->BuyTicket();
delete human;
//上来一位学生
human = new Student;
human->BuyTicket();
delete human;
}
标签:第一本,human,cout,C++,陈良乔,BuyTicket,Human,基类,函数 来源: https://blog.csdn.net/Alice_boy/article/details/86669030