在C++中,函数的形参是可以有默认值的。
默认参数只能放在参数列表的最后,即默认参数后面不能再有可变参数。
如果函数声明有默认值,则函数实现的时候就不能有默认参数。
语法:返回值类型 函数名(参数类型 参数名 = 默认值) {函数体}
#include
int func(int a, int b = 20, int c = 30) {
return a + b + c;
}
// test函数声明;如果函数声明中存在默认参数,则函数实现中就不能再有默认参数
int test(int a, int b = 20, int c = 30);
// test函数实现;该函数会报错,因为声明中已经存在默认参数,实现中又出现了默认参数
// int test(int a, int b = 20, int c = 30) {
// return a + b + c;
// }
// test函数实现
int test(int a, int b, int c) {
return a + b + c;
}
// eval函数声明;如果函数实现中存在默认参数,则函数声明中就不能再有默认参数
int eval(int a, int b, int c);
// eval函数实现
int eval(int a, int b = 20, int c = 30) {
return a + b + c;
}
int main() {
int a = 10;
int result1 = func(a);
int result2 = func(a, 50);
int result3 = func(a, 50, 100);
std::cout << result1 << std::endl;
std::cout << result2 << std::endl;
std::cout << result3 << std::endl;
int result4 = test(a);
int result5 = test(a, 50);
std::cout << result4 << std::endl;
std::cout << result5 << std::endl;
int result6 = eval(a);
int result7 = eval(a, 50);
std::cout << result6 << std::endl;
std::cout << result7 << std::endl;
system("pause");
return 0;
}
---------
60
90
160
60
90
60
90
小结:
在C++中,函数可以有占位参数,顾名思义其可以用来占位,调用函数时必须填补该位置。
占位参数也可以有默认参数。
语法:返回值类型 函数名(参数类型) {函数体}
#include
// 占位参数,直接用数据类型表示
void func(int a, int) {
std::cout << "this is a function" << std::endl;
}
// 占位参数也可以是默认参数
void test(int a, int = 10) {
std::cout << "hello test" << std::endl;
}
int main() {
func(10, 10); // 调用时需补上占位参数的值
test(10); // 默认参数可以不传实参
system("pause");
return 0;
}
---------
this is a function
hello test
作用:函数名可以相同,从而提高程序的复用性
函数重载满足如下条件:
注意:函数的返回值类型不可以作为函数重载的条件
#include
// 无参
void func() {
std::cout << "This is an parameterless function" << std::endl;
}
// 一个整型参数
int func(int a) {
return a;
}
// 一个双精度型参数
int func(double a) {
int x = int(a);
return x;
}
// 两个参数,其中一个为整型,另一个为双精度型
void func(int a, double b) {
std::cout << a / int(b) << std::endl;
}
// 调换参数顺序
void func(double a, int b) {
std::cout << int(a) / b << std::endl;
}
int main() {
func();
int result1 = func(10);
int result2 = func(3.14);
std::cout << result1 << std::endl;
std::cout << result2 << std::endl;
func(10, 5.2);
func(5.2, 10);
system("pause");
return 0;
}
---------
This is an parameterless function
10
3
2
0
const
与不加const
可以作为引用重载的条件#include
// 不加const的引用
void func(int& a) {
std::cout << "这是一个变量" << std::endl;
}
// 加const的引用
void func(const int& a) {
std::cout << "这是一个常量" << std::endl;
}
int main() {
int a = 10;
func(a);
const int b = 10;
func(b);
func(10);
system("pause");
return 0;
}
---------
这是一个变量
这是一个常量
这是一个常量
#include
void func(int a) {
std::cout << a << std::endl;
}
// 存在默认参数
void func(int a, int b = 10) {
std::cout << a + b << std::endl;
}
int main() {
// func(10); // 这会出现二义性,导致报错
func(10, 20);
system("pause");
return 0;
}
---------
30