函数默认参数
C++在声明函数原型的时可为一个或者多个参数指定默认的参数值,当函数调用的时候如果没有指定这个值,编译器会自动用默认值代替。
代码示例
#include <iostream>
/**
* 默认参数
*/
using namespace std;
/**
* 1、默认参数 ,可以给形参加默认值,如果传入值,就用用户传的实参,如果没有就用默认值
*/
//如果某个位置已经有了默认参数,那么从这个位置起,后面的参数都必须有默认参数。
int function(int a, int b = 20, int c =20){
return a + b + c;
}
// 声明函数
void test01(){
// 定义变量
int a = 10;
int b = 100;
// 输出结果
cout << function(a,b) << endl;
}
// 函数的声明和实现,只能有一个有默认参数
int function2(int a = 10, int b =10);
int function2(int a, int b){
return a + b;
}
void test02(){
function2();
}
int main() {
cout << "Hello, World!" << endl;
// 调用函数
// test01();
test02();
return 0;
注意点:
1、函数的默认参数从左向右,如果一个参数设置了默认参数,那么这个参数之后的参数都必须设置默认参数。
2、如果函数声明和函数定义分开写,函数声明和函数定义不能同时设置默认参数。
函数占位参数
C++在声明函数时,可以设置占位参数。==占位参数只有参数类型声明,而没有参数名声明。==一般情况下,在函数体内部无法使用占位参数。
代码示例
#include <iostream>
/*
函数的占位参数
*/
using namespace std;
void TestFunc01(int a,int b,int){
//函数内部无法使用占位参数
cout << "a + b = " << a + b << endl;
}
//占位参数也可以设置默认值
void TestFunc02(int a, int b, int = 20){
//函数内部依旧无法使用占位参数
cout << "a + b = " << a + b << endl;
}
int main() {
cout << "Hello, World!" << endl;
//错误调用,占位参数也是参数,必须传参数
//TestFunc01(10,20);
//正确调用
TestFunc01(10,20,30);
//正确调用
TestFunc02(10,20);
//正确调用
TestFunc02(10, 20, 30);
return 0;
}
函数重载
函数重载:C++下允许函数名称相同。
实现函数重载的条件:
- 同一个作用域。
- 参数个数不同。
- 参数类型不同。
- 参数顺序不同。
代码示例
#include <iostream>
/**
* 函数重载:C++下允许函数名称相同
*/
using namespace std;
// 声明函数
void function()
{
cout << "function()调用" << endl;
}
void function(int a)
{
cout << "function(int a)调用" << endl;
}
void function(int a, double b)
{
cout << "function(int a, double b)调用" << endl;
}
void test(){
function(3.23, 10);
}
int main() {
cout << "Hello, World!" << endl;
// 调用函数
test();
return 0;
}
参数const和无const的区别
代码示例
#include <iostream>
/**
* 函数重载:引用的两个版本,参数加const和不加const的区别
*/
using namespace std;
// 声明函数
void myFunction(int & a){
cout << "myFunction(int &a)的调用" << endl;
}
void myFunction(const int & a){
cout << "myFunction(const int &a)的调用"<< endl;
}
void test(){
// myFunction(10); // myFunction(const int &a)的调用
int a = 10;
myFunction(a); // myFunction(int &a)的调用
}
int main() {
cout << "Hello, World!" << endl;
// 调用函数
test();
return 0;
}
注意问题
函数重载和默认参数一起使用,需要额外注意二义性问题的产生。
代码示例
#include <iostream>
using namespace std;
// 定义函数
void myFunction(int a, int b=100){
cout << "myFunction(int a, int b)的调用" << endl;
}
void myFunction(int a){
cout << "myFunction(int a )的调用" << endl;
}
// 声明函数
void test(){
// myFunction(10); 二义性出现
}
int main() {
cout << "Hello, World!" << endl;
test();
return 0;
}