zoukankan      html  css  js  c++  java
  • 派生类重写方法

    #include <iostream>
    
    /* run this program using the console pauser or add your own getch, system("pause") or input loop */
    
    class Super
    {
        public:
            Super();
            virtual void someMether();
        protected:
            int mPritectedInt;
        private:
            int mPrivateInt;
    };
    
    class Sub : public Super
    {
        public:
            Sub();
            void someMether() override;    //重写父类的someMether方法 
            void someOtherMether();
        private:
            double mPrivateDouble;
    };
    
    Super::Super()
    :mPritectedInt(0)
    ,mPrivateInt(0)
    {
        
    }
    void Super::someMether()
    {
        std::cout << "Super's someMether
    " << std::endl;
    }
    
    Sub::Sub()
    :mPrivateDouble(0.0)
    {
        
    }
    void Sub::someMether()
    {
        std::cout << "Sub's someMether" << std::endl;
    }
    
    void Sub::someOtherMether()
    {
        std::cout << "Sub's someOtherMether" << std::endl;
    }
    
    int main(int argc, char** argv) 
    {
        Super super;
        Sub sub;
        sub.someMether();
        sub.someOtherMether();
        return 0;
    }

    首先声明的时只有在父类的方法前写上virtual关键字,派生类才能重写这个方法,

    建议在派生类的后边写上override,这并非是关键字,但是却起着关键字的作用,

    override由两个作用:

    1.在函数比较多的情况下可以提示读者某个函数重写了基类虚函数(表示这个虚函数是从基类继承,不是派生类自己定义的);

    2.强制编译器检查某个函数是否重写基类虚函数,如果没有则报错。

  • 相关阅读:
    thinkphp redis实现文章点赞功能并同步入mysql
    phpstorm2020.1最新版永久破解
    mysql修改sql_mode为宽松模式
    用为知发布博客到博客园、使用Wiz编写和发布博客园(cnblogs)博客
    Vim命令大全
    Vim教程
    GDB教程详解
    TCMalloc 对MYSQL 性能 优化的分析
    TCMalloc 安装和使用
    使用Tcmalloc进行堆栈分析
  • 原文地址:https://www.cnblogs.com/boost/p/10338087.html
Copyright © 2011-2022 走看看