Fork me on GitHub

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

posted @ 2019-12-24 15:48  西西嘛呦  阅读(230)  评论(0编辑  收藏  举报