1 函数的默认参数
在C++中,函数的形参列表中的形参是可以有默认值的。
语法:返回值类型 函数名 (参数=默认值)
#include<iostream>
using namespace std;
int func(int a = 10, int b = 20, int c = 30) {
return a + b + c;
}
int main() {
cout << func(20) << endl;
system("pause");
return 0;
}
运行结果:
如果传入自己输入的数据,就使用输入的数据,如果没有,就用默认值。
注意事项:
·如果某个位置已经有了默认参数,那么从这个位置往后,从左到右必须有默认值
·如果函数声明有默认参数,函数实现就不能有默认参数,声明和实现只能有一个默认参数
2 函数占位参数
C++中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该位置
占位参数也有默认参数
语法:返回值类型 函数名(数据类型){}
#include<iostream>
using namespace std;
void func(int a, int) {
cout << "this is func" << endl;
}
int main() {
func(20, 20);
system("pause");
return 0;
}
运行结果:
3 函数重载
作用:函数名可以相同,提高复用性
3.1 基本语法
函数重载满足条件:
同一个作用域下
函数名称相同
函数参数类型不同或者个数不同或者顺序不同
注意:函数的返回值不可以作为函数重载条件
#include<iostream>
using namespace std;
void func(int a) {
cout << "this is func(int a)" << endl;
}
void func(double a) {
cout << "this is func(int a)" << endl;
}
void func() {
cout << "this is func()" << endl;
}
void func(double a, int b) {
cout << "this is func(double a,int b)" << endl;
}
void func(int a, double b) {
cout << "this is func(double a,int b)" << endl;
}
int main() {
func(1);
func(1.2);
func();
func(1.2, 1);
func(1, 1.2);
system("pause");
return 0;
}
运行结果:
3.2 注意事项
引用作为重载条件
函数重载碰到函数默认参数
示例1
#include<iostream>
using namespace std;
//1.引用作为重载的条件
void func(int& a) {
cout << "func(int &a)调用" << endl;
}
void func(const int& a) {
cout << "func(const int &a)调用" << endl;
}
int main() {
int a = 10;
func(a);
func(10);
system("pause");
return 0;
}
运行结果:
引用的本质是指针常量,可以改变内容不能改变地址,所以int &a=10改变了地址,不合法。
示例2
#include<iostream>
using namespace std;
//2.函数重载碰到默认参数
void func(int a) {
cout << "func(int a)调用" << endl;
}
void func(int a, int b = 10) {
cout << "func(int a)调用" << endl;
}
int main() {
func(10);//错误,出现二义性
system("pause");
return 0;
}
当函数重载遇到默认参数,应该避免出现二义性