您的位置:首页 > 其它

多态应用举例2

2015-08-25 11:40 375 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: