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)不清楚会调用哪一个函数,报错。

  • 相关阅读:
    VS2010中添加MVC3和MVC4
    C#--对象转成XML的方法
    Web优化的措施
    Socket的使用(简单测试)
    WCF、WebAPI、WCFREST、WebService之间的区别
    Java和C#(笔记)
    各种窗口最小化快捷键详解
    SASS的安装及使用(前提:安装Ruby)
    查看Linux是32位还是64位
    log4j输出日志到文件
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12091927.html
Copyright © 2011-2022 走看看