zoukankan      html  css  js  c++  java
  • 揭秘继承技术之虚函数

    虚函数

    调用虚函数时函数行为将根据对象所属类的不同而变化。

    父类指针或引用指向子类对象时,可访问子类重写方法( virtual函数)但无法访问在父类中没有定义的子类方法和数据成员。

    #include <iostream>
    
    using namespace std;
    
    class Super
    {
    public:
        Super(){}
        virtual void where(){cout<<"there is Super"<<endl;}
    };
    
    class Sub :public Super
    {
    public:
        Sub(){}
        virtual void where(){cout<<"there is Sub"<<endl;}
        void what(){cout<<"what?";}
    };
    
    int main()
    {
        Sub sub;
        Super* ptr = &sub;
        Super &ref = sub;
    
        sub.where();
        ptr->where();
        ref.where();
    
        return 0;
    }

    运行结果:

    通过ptr和ref访问的where()均为子类方法,无法访问子类的what()方法。

    所有析构函数都应该声明为虚函数(至少祖先类的析构函数应声明为virtual)

    一个函数被声明为virtual即使在它子类中没有显式的指出该函数依然是virtual。

    如果父类的析构函数没有声明为virtual,当delete一个实际指向子类对象的父类指针时,析构函数调用链将被破坏。

    #include <iostream>
    
    using namespace std;
    
    class Something
    {
    public:
        Something(){cout <<"1";}
         ~Something(){cout<<"1";}
    };
    
    class Super : public Something
    {
    public:
        Super(){cout<<"2";}
        ~Super(){cout<<"2";}
    };
    
    class Sub :public Super
    {
    public:
        Sub(){cout<<"3";}
         ~Sub(){cout<<"3";}
    };
    
    int main()
    {
        Super* ptr = new Sub;
        delete ptr;
    
        return 0;
    }

    运行结果:

    将Something的析构函数声明为virtual后,结果就为“123321”了。

  • 相关阅读:
    bzoj 3670: [Noi2014]动物园
    bzoj 2878: [Noi2012]迷失游乐园
    51nod 1348 乘积之和
    51nod 1514 美妙的序列
    AtCoder Grand Contest 002 D
    bzoj 3451 Normal
    LOJ #6119. 「2017 山东二轮集训 Day7」国王
    51nod 1752 哈希统计
    计蒜客 百度地图的实时路况
    Codeforces 549F Yura and Developers
  • 原文地址:https://www.cnblogs.com/baiyideng/p/3601452.html
Copyright © 2011-2022 走看看