多态->虚函数


#include<iostream>
using namespace std;
class Father
{
    public:
        Father()
        {
            cout<<"father"<<endl;
        }
        Father(int)
        {
            cout<<"int father"<<endl;
        }
        ~Father()
        {
            cout<<"~father"<<endl;
        }
        virtual void show()
        {
            cout<<"father.show"<<endl;
        }
};

class Sun:public Father
{
    public:
        Sun()
            {
                cout<<"sun"<<endl;
            }
        Sun(int)
            {
                cout<<"int sun"<<endl;
            }
            ~Sun()
            {
                cout<<"~sun"<<endl;
            }
            void show()
            {
                cout<<"sun.show"<<endl;
            }
};

int main()
{   Sun s;
    Father f;
//  s.show();
//  f.show();
    Father *p=&s;//--------------不加virtual输出的是父类的show。

    p->show();
}

猜你喜欢

转载自blog.csdn.net/it8343/article/details/80496632