C++学习笔记(十六)——函数重载
一、 函数重载
作用:
函数重载(Function Overloading) 是 C++ 允许 多个同名函数 但参数不同 的一种特性。
- 通过参数的类型、个数或顺序区分不同的函数。
- 编译器会根据调用时提供的参数自动选择合适的函数。
特点:
- 函数名相同,但参数列表不同(参数类型、个数、顺序至少有一个不同)。
- 返回值类型不能作为区分重载的标准。
- 提高代码可读性,简化接口设计。
二、 函数重载的基本语法
语法:
返回类型 函数名(参数1, 参数2, ...);
返回类型 函数名(不同参数1, 不同参数2, ...);
示例:
#include <iostream>
using namespace std;
// 计算整数的平方
int square(int x)
{
return x * x;
}
// 计算双精度浮点数的平方
double square(double x)
{
return x * x;
}
int main() {
cout << "square(5) = " << square(5) << endl; // 调用 int 版本
cout << "square(2.5) = " << square(2.5) << endl; // 调用 double 版本
system("pause");
return 0;
}
注意:
square(int x)
和square(double x)
函数名相同,参数类型不同,属于重载函数。- 编译器自动匹配合适的重载版本。
三、函数重载的规则
(1)允许的重载情况
- 参数类型不同:
void func(int x); void func(double x);
- 参数个数不同:
void func(int x); void func(int x, int y);
- 参数顺序不同:
void func(int x, double y); void func(double x, int y);
(2)不允许的重载情况
-
仅返回值不同,参数列表相同:
int func(int x); double func(int x); // 错误,无法区分按返回值类型区分的函数
-
仅参数名称不同(参数类型相同):
void func(int a); void func(int b); // 错误,参数类型相同,函数重复定义
四、 应用案例
(1) 函数重载——自动调用匹配的重载版本
示例——计算不同数据类型的绝对值:
#include <iostream>
using namespace std;
// 绝对值计算(int 版本)
int absVal(int x)
{
return (x < 0) ? -x : x;
}
// 绝对值计算(double 版本)
double absVal(double x)
{
return (x < 0) ? -x : x;
}
int main() {
cout << "absVal(-10) = " << absVal(-10) << endl;
cout << "absVal(-5.5) = " << absVal(-5.5) << endl;
system("pause");
return 0;
}
注意:
根据参数类型,编译器自动调用匹配的重载版本。
(2) 函数重载 + 默认参数
示例——计算面积:
#include <iostream>
using namespace std;
// 计算矩形面积(默认参数)
int area(int length, int width = 10)
{
return length * width;
}
// 计算圆面积
double area(double radius)
{
return 3.14159 * radius * radius;
}
int main() {
cout << "矩形面积: " << area(5) << endl; // 使用默认参数
cout << "矩形面积: " << area(5, 6) << endl; // 传入两个参数
cout << "圆的面积: " << area(3.0) << endl; // 调用 double 版本
system("pause");
return 0;
}
注意:
area(int, int)
有默认参数,调用时如果省略参数,则使用默认值。area(double)
计算圆的面积,自动匹配合适的重载版本。
(3) 函数重载 + 类型转换
可能出现的问题:
如果一个重载函数和隐式类型转换冲突,可能导致歧义(Ambiguous)。
示例:
#include <iostream>
using namespace std;
// int 版本
void func(int x)
{
cout << "int 版本" << endl;
}
// char 版本
void func(char x)
{
cout << "char 版本" << endl;
}
int main() {
func(10); // 调用 int 版本
func('A'); // 调用 char 版本
// func(2.5); // 错误, 可能调用 int 或 char,导致歧义
system("pause");
return 0;
}
注意:
- 使用
explicit
类型转换:func(static_cast<int>(2.5)); // 强制使用 int 版本
- 避免过多的自动类型转换。
(4) const
引用重载
示例——const引用重载:
#include <iostream>
using namespace std;
void print(int& x)
{
cout << "普通引用" << endl;
}
void print(const int& x)
{
cout << "const 引用" << endl;
}
int main() {
int a = 10;
const int b = 20;
print(a); // 调用非 const 版本
print(b); // 调用 const 版本
print(30); // 传递临时变量,调用 const 版本
system("pause");
return 0;
}
注意:
print(int &x)
只能绑定非const
变量。print(const int &x)
可以绑定const
变量或临时值。