多态应用举例2

#include<iostream>
class Base{
    public:
        void fun1(){
            this->fun2();//this 基类指针 fun2虚函数 所以是多态
        }
        virtual void fun2(){
            cout <<"Base::fun2()"<<endl;
        }
};
class Derived:public Base{
    public:
        virtual void fun2(){
            cout<<"Derived::fun2()"<<endl;
        }
};
int main(){
    Derived d;
    Base * pBase = &d;
    pBase->fun1();//pBase ->fun1 this指针就是指向子类的对象 调用 子类fun2函数
    return 0;
}

//得出结论 非构造函数,非析构函数的成员函数中调用虚函数就是多态
//在构造函数和析构函数中调用虚函数不是多态,在编译时候就可以确定,
//调用的函数是自己的类或基类中定义的函数,不会等到运行时候才决定调用是自己的还是派生类的函数
class myclass{
    public:
        virtual void hello(){
            cout<<"hello from myclass"<<endl;
        
        }
        virtual void bye{
            cout<<"bye from myclass"<<endl;
        }
};
class son:public myclass{
    public:
        void hello(){//派生类中和基类中虚函数同名同参数表的函数 不加virtual 也自动成为虚函数
            cout<<"hello from son"<<endl;
            
        }
        son(){
            hello();
        }
        ~son(){
            bye();
        }
};


class grandson:public son{
    public:
        void hello(){
            cout<<"hello from grandson"<<endl;
            
        }
        void bye(){
            cout<<"bye from grandson"<<endl;
            
        }
        grandson(){cout<<"constructing grandson"}
        ~grandson(){
            cout<<"destructing grandson"<<endl;
        }
};


int main(){
    grandson gson;
    son*pson;
    pson= &gsion;
    pson->hello();//多态
    
    return 0;
}







































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值