利用虚函数实现多态

关键字 virtual 

针对基类的不同派生类,如果派生类重新定义虚函数,那么派生类的虚函数将覆盖基类对应虚函数的实现。如果强制派生类定义某个函数,则可以在基类中将这个虚函数声明为纯虚函数,也就是基类不实现这个虚函数,所有实现留给派生类。

当类中含有纯虚函数时,这个类就是抽象类。不能创建抽象类的对象,否则出现编译错误。如果某个类从抽象类中派生,就必须实现其中的纯虚函数,才能成为一个实体类,否则继续保持抽象类的特征。

virtual.h

#ifndef ABC
#define ABC
#include <iostream>
#include <string>
using namespace std;

class human
{
        public:
                virtual void Buyticket()=0;//声明为纯虚函数,留给派生类实现
};
class teacher :public human
{

        public:
                virtual void Buyticket()
                {
                cout<<"teacher ---buying.... "<<endl;
                }
};
class student : public human
{
        public:
                virtual void Buyticket()
                {
                cout<<"student----buying....."<<endl;
                }

};

#endif


main.cpp

#include <iostream>
#include "virtual.h"
using namespace std;

int main ()
{
        human* A ;
        A =new teacher();
        A->Buyticket();
        delete A;
        A= new student();
        A->Buyticket();
        A=NULL;

return 0;
}
~

输出:

teacher ---buying....
student----buying.....


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值