> 文章列表 > 【C++】C++核心编程(三)---函数高级

【C++】C++核心编程(三)---函数高级

【C++】C++核心编程(三)---函数高级

1.函数的默认参数

在C++中,函数的形参列表中的形参是可以有默认值的。

语法:返回值类型 函数名(参数 = 默认值){ 函数体语句;}

函数默认参数设置的注意事项

  1. 如果形参列表中的某个位置有了默认值,那么从这个位置开始,从左至右,必须都要有默认值
  2. 如果函数的申明有了默认值,函数实现的时候就不能有默认值,也就是说,函数的申明和定义只能有一种情况下出现默认值
  • 代码演示:
#include <iostream>
using namespace std;// 函数的默认参数
int func1(int a = 1119, int b = 2023)
{return a + b;
}// 注意事项一:报错(默认实参不在形参列表的结尾)
//int func2(int a = 1119,int b)
//{
//	return a + b;
//}// 注意事项二:报错(func3重定义默认参数)在调用函数的时候编译器不知道使用哪个默认参数
//int func3(int a = 1119, int b = 2023);
int func3(int a,int b);
int func3(int a = 1119, int b = 2022)
{return a + b;
}int main() {cout << func1() << endl;cout << func3() << endl;system("pause");return 0;
}
  • 输出结果:
3142
3141
请按任意键继续. . .

2.函数的占位参数

C++中的形参列表里可以有占位参数,用来占位,调用函数时必须填补该位置

语法:返回值类型 函数名(数据类型){函数体语句;}

  • 代码演示:
#include <iostream>
using namespace std;void func(int a,int)
{cout << "函数func的占位参数" << endl;
}int main() {func(10,10); // 占位参数在函数调用时必须填补上system("pause");return 0;
}
  • 输出结果
函数func的占位参数
请按任意键继续. . .

3.函数重载

3.1基本语法

函数重载的作用:函数名可以相同,提高代码的复用性

函数重载满足的条件

  1. 在同一个作用域下;(全局作用域、public、private等)
  2. 函数名相同
  3. 函数参数类型不同、或者个数不同、或者顺序不同

注意:函数的返回值不能够作为函数重载的条件。

  • 代码演示:
#include <iostream>
using namespace std;// 如果不满足函数重载的条件,编译器将会报错。函数...已有主体
void func1()
{cout << "func1的调用!" << endl;
}void func1(int a)
{cout << "func1(int a)的调用!" << endl;
}void func1(int a,double b)
{cout << "func1(int a,double b)的调用!" << endl;
}void func1(double a,int b)
{cout << "func1(double a,int b)的调用!" << endl;
}// 函数的返回值不能作为函数重载的条件,报错:无法返回仅按返回类型区分的函数
//int func1(double a, int b)
//{
//	cout << "func1(double a,int b)的调用!" << endl;
//}int main() {func1();func1(1119);func1(1119,2022.1119);func1(2022.1119,1119);system("pause");return 0;
}
  • 输出结果:
func1的调用!
func1(int a)的调用!
func1(int a,double b)的调用!
func1(double a,int b)的调用!
请按任意键继续. . .

3.2注意事项

函数重载的注意事项

  1. 引用作为重载条件;
  2. 函数重载碰到默认参数。
  • 代码演示:
#include <iostream>
using namespace std;// 1、引用作为重载条件
void func(int& a) // int& a = 10; 不合法,int& a = b; 合法
{cout << "func(int& a)的调用!" << endl;
}void func(const int& a) // const int& a = 10; 合法,const int& a = b; 不合法
{cout << "func(const int& a)的调用!" << endl;
}// 2、函数重载碰到默认参数
void func1(int a,int b = 10)
{cout << "func1(int a,int b = 10)的调用!" << endl;
}void func1(int a)
{cout << "func1(int a)的调用!" << endl;
}int main() {int a = 10;func(a); // 调用func(int& a)这个函数func(10); // 调用func(const int& a)这个函数//func1(10); //报错:有多个重载函数func1实例与参数列表匹配func1(10,20);system("pause");return 0;
}
  • 输出结果:
func(int& a)的调用!
func(const int& a)的调用!
func1(int a,int b = 10)的调用!
请按任意键继续. . .