一、函数的默认参数
在C++中,函数的形参列表中的形参是可以有默认值的。
语法:返回值类型 函数名 (参数=默认值){}
示例:函数的默认参数
int func (int a=10,int b=10,int c=20)
{
return a+b+c;
}
示例1:
#include <iostream>
#include "other.h"
using namespace std;
int func(int a=10,int b=20,int c=20)
{
return a+b+c;
}
int main()
{
cout<<func()<<endl;
return 0;
}
示例2:
#include <iostream>
#include "other.h"
using namespace std;
int func(int a=10,int b=20,int c=20)
{
return a+b+c;
}
int main()
{
cout<<func(50,30)<<endl;
return 0;
}
结果:
结论:
如果我们自己传了数值,那就用我们自己传入的值,如果没有传入值,那就使用默认值。
注意:如果函数当中的形参有默认值,那从这个之后的每个形参都必须要有一个默认值
示例:看一下以下这几种写法都对吗?
1.
int func(int a=10,int b,int c)
{
return a+b+c;
}
2.
int func(int a,int b=10,int c)
{
return a+b+c;
}
3.
int func(int a=10,int b,int c=1)
{
return a+b+c;
}
示例:正确的写法
int func(int a,int b,int c=1)
{
return a+b+c;
}
或
int func(int a,int b=1,int c=1)
{
return a+b+c;
}
或
int func(int a=1,int b=1,int c=1)
{
return a+b+c;
}
注意:如果函数当中的形参有默认值,那从这个之后的每个形参都必须要有一个默认值
二、函数的占位参数
C++中函数的形参列表里可以有占位参数,用来做寿占位,调用函数时必须填补该位置
语法:返回值类型 函数名 (数据类型) {}
在现阶段函数的占位参数存在的意义不大,但是后面的课程中会用到该技术
示例:函数的占位参数
void func(int a,int) //这里就是占位参数,只写了一个类型,并没有变量
{
cout<<"this is a func"<<endl;
}
int main()
{
func(10,10);
return 0;
}
这里的void func(int a,int) //这里的int就是占位参数,只写了一个类型,并没有变量。在实际调用当中,占位参数必须要赋上实际的值。
示例2:占位参数可以有默认值
void func(int a,int=10)
这里的void func(int a,int=10) //这里的int=10就是占位参数的默认值,那在函数的实际调用时,可以不用给占位参数赋值。
三、函数重载
1、函数重载概述
作用:函数名可以相同,提高复用性,根据参数不同来实现不同的功能。
函数重载满足条件:
- 同一个作用域下
- 函数名相同
-
示例:函数重载
void func() { cout<<"func的调用" } void func(int a) { cout<<"func(int a)的调用" } void func(double a) { cout<<"func(double a)的调用" }
以上三个函数是相同的名字,但是根据函数的形参不同,可以形成不同的调用,这个就是函数重载。
注意:不能根据函数的返回类型构成函数重载条件,只能是根据形参构成函数重置2、函数重载注意事项
引用做为重载条件
- 函数重载碰到函数默认参数
2.1、当引用作业函数重载的条件时
示例1:void func(int &a)函数重载的调用
```cppinclude
include “other.h”
using namespace std;
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); //这里是重点 }
**结果:**<br />****
<a name="lD5Bv"></a>
#### 示例2:void func(const int &a)函数重载的调用
```cpp
#include <iostream>
#include "other.h"
using namespace std;
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(10); //这里是重点
}
2.2当函数重载碰到默认参数时
示例:
#include <iostream>
#include "other.h"
using namespace std;
void func(int a,int b=10)
{
cout << "func(int a,int b=10)的调用" << endl;
}
void func( int a)
{
cout << "func(int a)的调用" << endl;
}
int main()
{
func(10);
}
结果:
注意:当函数重载有默认参数时,一定要注意这种情况,函数调用的这个两个函数重载都能调进去,所以编译器产生了错误