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”了。

  • 相关阅读:
    功能测试--电梯测试项
    进程
    基于UDP协议的socket编程
    自定义报头解决粘包问题
    基于TCP协议的socket编程
    python3 中encode 和decode的使用方法。
    反射---hasattr、getattr、setattr、delattr
    摘要算法---hashlib模块下MD5和SHA的使用
    日志模块---logging
    staticmethod、classmethod的使用
  • 原文地址:https://www.cnblogs.com/baiyideng/p/3601452.html
Copyright © 2011-2022 走看看