C++学习记录-函数的重载

一、函数重载

重载的意义:使用相同的函数名,但传入的参数和函数内部的方法有所不同,提高了代码的复用性。

二、重载的条件

函数的参数不同:参数个数,参数类型,参数顺序等

函数的返回值不可作为重载的条件!!

示例:

1
2
3
4
5
6
7
8
9
10
11
12
//函数的重载
void fun()
{
cout<<"fun()"<<endl;
}

void fun(int a)
{
cout<<"fun(int a)"<<endl;
}

//对fun函数进行了重载,调用时程序会根据传入的参数来调用不同的函数

三、函数重载遇到引用和默认值的情况

遇到引用:

1
2
3
4
5
6
7
8
9
10
void fun(int &a)
{
cout<<"int &a"<<endl;
}

void fun(const int &a)
{
cout<<"const int &a"<<endl;
}
//以上对fun函数进行了重载

此时,对fun函数传入参数,有:

1
2
3
4
5
6
7
int a = 10;
fun(a);
//此时会调用打印 int &a 的函数

int a = 10;
fun(10);
//此时会调用打印 const int &a 的函数

原因:第一个fun是引用传递,需要传入一个具体的地址。

​ 第二个fun在引用传递之前有const修饰,可以传入一个常量

遇到默认值:

1
2
3
4
5
6
7
8
9
void fun(int a)
{
cout << "int a" << endl;
}

void fun(int a, int b = 10)
{
cout << "int a,int b=10" << endl;
}

此时传入数据:

1
2
3
int a = 10;
fun(a,20);
//会调用第二个fun

但如果只传入一个数据:

1
2
3
int a = 10;
fun(a);
//报错

1>D:\Work\C艹练习\练手\Project1\Project1\源.cpp(21,10): error C2668: “fun”: 对重载函数的调用不明确
1>D:\Work\C艹练习\练手\Project1\Project1\源.cpp(12,6): message : 可能是“void fun(int,int)”
1>D:\Work\C艹练习\练手\Project1\Project1\源.cpp(7,6): message : 或 “void fun(int)”
1>D:\Work\C艹练习\练手\Project1\Project1\源.cpp(21,10): message : 尝试匹配参数列表“(int)”时

此时会产生二义性,在编程时应避免