目录
函 数 的 默 认 参 数
函 数 的 占 位 参 数
函 数 重 载 的 基 本 语 法
????????参数个数不同
?????????参数类型不同
?????????参数顺序不同
?????????注意事项
?函 数 重 载 的 注 意 事 项
????????引用作为重载条件
?????????函数重载碰到函数默认参数
函 数 的 默 认 参 数
一般函数,a,b,c 都是函数形式参数
int add(int a, int b, int c)
{
return a + b + c;
}
默认参数,在参数内赋值,可以省去 传入参数 b 和 c,
只传入 a?
int add(int a, int b = 10, int c = 20)
{
return a + b + c;
}
int main()
{
cout << add(1) << endl;
system("pause");
return 0;
}

传入 a 的同时也传入 b 和 c
int add(int a, int b = 10, int c = 20)
{
return a + b + c;
}
int main()
{
cout << add(1, 2, 3) << endl;
system("pause");
return 0;
}

如果在函数参数中 有 对参数进行赋值,
函数调用时??未进行? 传值就使用? 默认值,
函数调用时??进行了? 传值就使用? 传入的数值。
注意事项 1:如果某个位置已经有了默认参数,那么这个位置从左到右到要有默认值

?error C2548: “add”: 缺少形参 3 的默认实参
注意事项 2:如果函数声明有默认参数,函数实现就不能有默认参数,实现有声明就不能有,建议将默认参数放在实现
int testc(int a = 10, int b = 20); // 函数声明
int testc(int a = 10, int b = 20) // 函数实现
{
return a + b;
}
int main()
{
testc();
return 0;
}
error C2572: “testc”: 重定义默认参数 : 参数 1
message : 参见“testc”的声明
error C2572: “testc”: 重定义默认参数 : 参数 2
message : 参见“testc”的声明
函 数 的 占 位 参 数
C++的函数列表里可以有占位参数,用来做占位,调用函数时必须填补该位置
-
语法:返回值类型? ?函数名? ?( 数据类型 )? ? { }?
这个 数据类型 就是占位参数
占位参数还可以有默认参数
void Fun(int a, char, int b = 20) // char ,int b = 20 为占位参数
{
cout << "占位参数" << endl;
}
int main()
{
Fun(10, 'a');
Fun(10);
system("pause");
return 0;
}
char ,int b = 20 ?为占位参数
函 数 重 载 的 基 本 语 法
作用:函数名可以相同,提高?复用性
-
函数重载满足条件:
- 同一作用域下
- 函数名称相同
- 函数?参 数 类 型?不同? ?或者?参 数 个 数 不同? ?或者 参 数 顺 序 不同
-
注意:函数返回值不可以作为函数重载的条件
参数个数不同
调用函数时没有传入参数,执行没有带参数的函数?

?调用函数时传入参数,执行含有对应参数的函数

?参数类型不同
?传入参数为 整形 就执行 参数为整形 的函数

?参数顺序不同

?注意事项
函数的返回值不可以作为函数重载的条件,
因为即使函数有返回值在调用的时候也可以不使用函数的返回值,所以还是无法区分

?函 数 重 载 的 注 意 事 项
引用作为重载条件
-
函数重载碰到函数默认参数
引用作为重载条件
void test(int& a)
{
cout << "hello" << endl;
}
void test(const int& a)
{
cout << "world" << endl;
}
int main()
{
test(10); // 调用有 const 版本的
return 0;
}
?传入 const 常量类型,执行参数为 const int& a 的函数
理解为 :const int& a = 10;
int& a = 10; 这个是不合法的

void test(int& a)
{
cout << "hello" << endl;
}
void test(const int& a)
{
cout << "world" << endl;
}
int main()
{
int a = 10;
test(a); // 调用 无const 版本的
system("pause");
return 0;
}
?传入变量 a ,执行 参数为 int& a 的函数
理解为 :int& a = a;
变量 a 是可读可写的

?函数重载碰到函数默认参数

?test(10);? ?
可以调用? test1(int a, int b = 10)? 这个含有默认参数的函数,
也可以调用 test1(int a) 这个函数
编译器无法处理,重载碰到函数默认参数可能会导致?二义性?
为避免可能的错误,函数重载时,在函数参数后面避免加入 默认参数
|