• C++函数重载,重写,重定义


      笔者原创,转载请注明出处

      C++中经常会提到重载,除了重载,还有重写,重定义,下面对这三个概念逐一进行区分

    1 重载

      函数重载是同一定义域中(即同一个类中)的同名函数,但形参的个数必须不同,包括参数个数,类型和顺序,不能仅通过返回值类型的不同来重载函数

    #include<iostream>
    using namespace std;
    
    class BOX
    {
        void func(int a, int b, int c){} 
       
        void func(int a, int b){} // 参数个数不同
    
        void func(int c, int b, int a){} // 参数顺序不同
    
        int func(int a, int b, int c){} // **返回值类型不同,不能说明是重载函数**
    };
    
    int main()
    {
        BOX box;
    
        return 0;
    }
    

    2 重写

      在父类和子类中,并且函数形式完全相同,包括返回值,参数个数,类型和顺序
      父类中有vietual关键字,可以发生 多态

    #include<iostream>
    using namespace std;
    
    class BOX
    {
        virtual void func(int a, int b, int c = 0) //  函数重写 
        {
    
        }
    
    };
    
    class squareBox: public BOX
    {
        void func(int a, int b, int c = 0)
        {
    
        }
    };
    
    int main()
    {
        BOX box;
       
        return 0;
    }
    

    3 重定义

      重定义和函数重写类似,不同的地方是重定义父类中没有vietual关键字,不可以发生 多态

    #include<iostream>
    using namespace std;
    
    class BOX
    {
        void func(int a, int b, int c = 0) //**没有virtual关键字,函数重定义**
        {
    
        }
    
    };
    
    class squareBox: public BOX
    {
        void func(int a, int b, int c = 0)
        {
    
        }
    };
    
    int main()
    {
        BOX box;
       
        return 0;
    }
    

    4 函数重载二义性

      当函数重载遇上默认参数时,会出现二义性
      如下代码所示:

    #include<iostream>
    using namespace std;
    
    class BOX
    {
        void func(int a, int b, int c = 0)
        {
    
        }
    
        void func(int a, int b)
        {
    
        }
    };
    
    int main()
    {
        BOX box;
        box.func(1, 2); // **此函数不知道调用上面哪一个**
    
        return 0;
    }
    

    此博文随着笔者的学习会持续更新

    如有错误之处,敬请指正,万分感谢!

  • 相关阅读:
    Prometheus 简介
    Cassandra spring data 试用
    nginx fastcgi 优化
    mysql 用户管理
    js之iframe子页面与父页面通信
    ORACLE中SID和SERVICE_NAME的区别
    报“ Got minus one from a read call”的错误
    linux下重启oracle服务:监听器和实例
    25种提高网页加载速度的方法和技巧
    如何让你的网页加载时间降低到 1s 内
  • 原文地址:https://www.cnblogs.com/MisterXu/p/10651889.html
Copyright © 2020-2023  润新知