1.函数形参的默认参数
函数在声明或者实现时可以设置默认值,但是形参的默认值不可重复定义(在声明时设置不可再实现里设置)
语法 返回值类型 函数名 (形参=默认值){}
#include <iostream>
#include <string>
using namespace std;
int func(int a, int b = 10, int c = 20) //函数设置默认参数,若有传入数据,则使用传入值
//若某个位置已经有了默认参数,那么这个形参的后面的所有数据必须都要设定
//声明和实现只能有一个设定默认参数
{
a += b + c;
return a;
}
int main()
{
func(10);
cout << func(10) << endl;
cout << func(10, 20) << endl;
system("pause");
return 0;
}
若某个位置已经有了默认参数,那么这个形参的后面的所有数据必须都要设定
2.函数占位参数
语法:返回值类型 函数名 (数据类型){}
int func(int,int =10)
占位参数可以有默认参数
3.函数的重载
作用:C++允许函数名相同,提高复用性
函数重载的满足条件:
函数都在同一个作用域下
函数名称相同
函数参数的类型不同,或者个数不同,或者顺序不同
函数的返回类型不能作为区分重载条件
#include <iostream>
#include <string>
using namespace std;
void func()
{
cout << "函数1" << endl;
}
void func(int a)
{
cout << "函数" << a << endl;
}
int main()
{
func(10);
func();
system("pause");
return 0;
}
4.数重载的注意事项函
4.1 引用与函数重载
#include <iostream>
#include <string>
using namespace std;
void func(const int &a)
{
cout << "函数1常量引用" << endl;
}
void func(int &a)
{
cout << "函数2引用" << a << endl;
}
int main()
{
int a=10;
func(10);//输入为常量时,编译器会选择常量引用
func(a);//输入为变量时,选择引用函数
system("pause");
return 0;
}
4.2 默认参数与函数重载
有可能会出现二义性。
|