重载作用:
函数名可以相同,提高函数复用性;
函数重载需要满足的条件:
1.同一个作用域下;
2.函数名相同;
3.函数参数 类型不同 或者 个数不同 或者 顺序不同
而函数的返回值不可以作为函数重载的条件
//函数重载
#include<iostream>
#include<string>
using namespace std;
//都位于全局作用域
void a_sum(int a,int b) {
cout <<"void a_sum(int a,int b)" << endl;
}
void a_sum(string a, int b) { //参数类型不同
cout << "void a_sum(string a,int b)" << endl;
}
void a_sum(int a) { //参数个数不同
cout << "void a_sum(int a)" << endl;
}
void a_sum(int a, string b) { //参数顺序不同
cout << "void a_sum(int a,string b)" << endl;
}
/*
int a_sum(int a,string b){ //返回类型不同不可以作为重载的条件
cout << a << " " <<b << " : 4 " << endl;
}
*/
int main() {
int a = 10, b = 20;
string s = "sss";
string ss = "sssss";
a_sum(a, b);
a_sum(s, b);
a_sum(a);
a_sum(a, ss);
return 0;
}
注意事项:
1.引用作为重载的条件
2.函数重载与默认参数
当使用函数重载的时候,尽可能不要使用默认参数,否则很容易出错,出现二义性;
int &a与const int &a的区别:
函数中const int& a与int& a的区别_const vector<int> &a_小魔王降临的博客-CSDN博客