函数重载概述
作用:函数名相同可以相同,提高复用性
函数重载条件
- 同一作用域
- 函数名相同,函数返回值类型相同
- 函数参数列表不完全相同!!!(参数类型,个数,顺序)
总结,函数重载需在同一作用域下,只有函数参数列表不完全相同!!!
#include <iostream>
using namespace std;
void fun(int a){
cout << "fun(int a)" << endl;
}
//函数返回值类型不同不能作为函数重载条件
//int fun(int a){
// cout << "fun(int a)" << endl;
// return 0;
//}
void fun(int a, int b){
cout << "fun(int a, int b)" << endl;
}
void fun(int a, double b){
cout << "fun(int a, double b)" << endl;
}
void fun(double b, int a){
cout << "fun(int a, double b)" << endl;
}
int main() {
fun(10);
fun(10, 20);
fun(10, 20.0);
fun(20.0, 10);
return 0;
}
函数重载注意事项
引用作为重载条件
#include <iostream>
using namespace std;
void fun(int &a){ //变量的引用
cout << "fun(int &a)" << endl;
}
void fun(const int &a){ //常量的引用
cout << "fun(const int &a)" << endl;
}
int main() {
int a = 20;
fun(a); //a为变量,优先走fun(int &a), 此处是变量的引用
fun(10); //10为常量,优先走fun(const int &a),此处是常量的引用
return 0;
}
当我们执行fun(10)时,参事10无法传递给fun(int &a),因为int &a = 10是违法的。参数10只能传递给fun(const int &a),因为const int &a 会做以下步骤:
int temp = 10;
const int &a = temp;
函数重载碰到函数默认参数
#include <iostream>
using namespace std;
void fun(int a){
cout << "fun(int a)" << endl;
}
void fun(int a, int b = 10){
cout << "fun(int a, int b = 10)" << endl;
}
int main() {
fun(10); //错误
return 0;
}
如果不调用fun(10)程序不会出错。
如果调用,上面定义的两个函数均可使用,便会出现二义性,报错。