zoukankan      html  css  js  c++  java
  • c++之函数重载

    作用:函数名可以相同,提高复用性。

    喊出重载满足条件:

    • 同一个作用域;
    • 函数名相同
    • 函数参数类型不同或者个数不同或者顺序不同;
    #include<iostream>
    using namespace std;
    
    //函数重载需要函数在同一个作用域下
    void func() {
        cout << "调用func()" << endl;
    }
    void func(int a) {
        cout << "调用func(int a)" << endl;
    }
    void func(float a) {
        cout << "调用func(float a)" << endl;
    }
    void func(int a,float b) {
        cout << "调用func(int a,float b)" << endl;
    }
    void func(float a,int b) {
        cout << "调用func(float a,int b)" << endl;
    }
    void func(int a,int b,int c) {
        cout << "调用func(int a,int b,int c)" << endl;
    }
    
    
    int main() {
        func();
        func(1);
        func(1.2f);
        func(1, 1.2f);
        func(1.2f, 1);
        func(1, 2, 3);
        system("pause");
        return 0;
    }

    输出:

    函数重载注意事项:

    • 引用作为从重载条件
    • 函数重载碰到函数默认参数
    #include<iostream>
    using namespace std;
    
    void func(int& a) {
        cout << "调用func(int &a)" << endl;
    }
    void func(const int& a) {
        cout << "调用func(const int &a)" << endl;
    }
    
    int main() {
        int a = 10;
        func(a);//这里调用的是func(int &a)
        func(10);//这里调用的是func(const int &a)
        system("pause");
        return 0;
    }

    输出:

    #include<iostream>
    using namespace std;
    
    void func(int a,int b = 20) {
        cout << "调用func(int a,int b = 20)" << endl;
    }
    void func(int a) {
        cout << "调用func(int a)" << endl;
    }
    
    int main() {
        func(10);
        system("pause");
        return 0;
    }

    这种情况下,func(10)不清楚会调用哪一个函数,报错。

  • 相关阅读:
    样本间相似度/距离的计算方法总结
    package.json字段全解
    使用Charles对Https请求进行抓包
    URI和URL的区别
    webstorm常用快捷键
    HTML中判断手机是否安装某APP,跳转或下载该应用
    Git 常用命令大全
    vue的测试(Vue.js devtool)
    js求两个数的最大公约数
    javascript实现验证身份证号的有效性并提示
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12091927.html
Copyright © 2011-2022 走看看