3 C++函数提高
3.1 函数默认参数
- 在C++中,函数的形参列表中的形参是可以有默认值的
- 语法:函数返回类型 函数名 (参数=默认值){ }
示例1:
#include<iostream>
using namespace std;
//函数默认值
int func(int a, int b, int c)
{
return a + b + c;
}
int main()
{
cout<<func(10, 20, 30)<<endl;
system("pause");
}
输出为60;
示例2:
#include<iostream>
using namespace std;
//函数默认值
int func(int a, int b=30, int c=40)
{
return a + b + c;
}
int main()
{
cout<<func(10)<<endl;
system("pause");
}
输出为80;
示例3:
#include<iostream>
using namespace std;
//函数默认值
//如果我们自己传入的数据,就用自己的数据,如果没有,那么用默认值
int func(int a, int b=30, int c=40)
{
return a + b + c;
}
int main()
{
cout<<func(10,20)<<endl;
system("pause");
}
输出为 70;
t 示例4:
注意
- 如果某个位置有了默认参数,从这个位置往后,从左到右都必须有默认值。
int func(int a, int b=30, int c)
这样是不对的。 - 函数声明有默认参数,函数实现就不能有默认参数。声明和实现只能有一个地方有默认参数。也就是说,函数实现有默认参数,声明也不可以有默认参数。
int func(int a=10,intb=10)
.........................
.........................
.........................
int func(int a=10;int b=10)
{
return a+b;
}
system("pause");
重定义默认参数,这样会报错;
3.2 函数的占位参数
- C++中函数的形参列表里可以有占位参数,用来占位,调用函数时必须弥补该位置。
- 语法: 返回值类型 函数名(数据类型){ }
示例1:
#include<iostream>
using namespace std;
//占位参数
void func(int a, int)
{
cout << "this is a func" << endl;
}
int main()
{
func(10, 10);
system("pause");
}
示例2:占位参数还可以有默认值
#include<iostream>
using namespace std;
//占位参数
void func(int a, int = 10)//占位参数还可以有默认值
{
cout << "this is a func" << endl;
}
int main()
{
func(10, 10);
system("pause");
}
3.3 函数重载
3.3.1 函数重载概述
- 作用:函数名可以相同,提高复用性。
- 函数重载的需要满足的条件:1、同一个作用域下;2、函数名称相同;3、函数参数类型不同或者个数不同或者顺序不同。
- 注意函数的返回值不可以作为函数重载的条件。
示例1:个数不同
#include<iostream>
using namespace std;
//函数重载
void func()
{
cout << "this is a func1" << endl;
}
void func(int a)
{
cout << "this is a func2" << endl;
}
int main()
{
func(10);
func();
system("pause");
}
输出:
示例2:类型不同
#include<iostream>
using namespace std;
//函数重载
void func(double a)
{
cout << "this is a func1" << endl;
}
void func(int a)
{
cout << "this is a func2" << endl;
}
int main()
{
func(10);
func(0.1);
system("pause");
}
输出:
示例3:顺序不同
#include<iostream>
using namespace std;
//函数重载
void func(double b, int a)
{
cout << "this is a func1" << endl;
}
void func(int a,double b)
{
cout << "this is a func2" << endl;
}
int main()
{
func(10,0.1);
func(0.1,10);
system("pause");
}
3.3.2 函数重载注意事项
- 引用作为重载条件
- 函数重载碰到函数默认参数
示例1:引用作为重载
#include<iostream>
using namespace std;
void fun(int& a)
{
cout << "fun(int &a)调用" << endl;
}
void fun(const int &a)
{
cout << "fun(const int &a)调用" << endl;
}
int main()
{
int a = 10;
fun(a);
fun(10);
system("pause");
}
输出:
示例2:函数默认参数作为重载条件
#include<iostream>
using namespace std;
void fun(int a,int b=10)
{
cout << "fun(int a,int b=10)" << endl;
}
void fun(int a)
{
cout << "fun(int a)" << endl;
}
int main()
{
int a = 10;
int b=1;
fun(a, b);//必须有俩参数,不然不知道调用那个重载函数
system("pause");
}
输出: