C++ note------函数

本文深入探讨C++中函数的高级特性,包括默认参数、占位参数的使用规则及注意事项,函数重载的多种方式及其限制条件。通过具体代码示例,详细解释如何在实际编程中应用这些特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、默认参数

返回值类型 函数名(形参=默认值)

如果自己调用函数,对应的参数没有传入数据,则使用该参数默认值,否则使用传入值

#include <iostream>
using namespace std;

//b,c默认值为20,30
int fun(int a, int b=20, int c=30) {
	return a + b + c;
}

int main()
{
	cout << fun(10) << endl;
	cout << fun(10,30) << endl;
	system("pause");
	return 0;
}

输出:60	70

warning:

1、如果某个形参定义了默认值,那么从这个形参开始,从左往右的所有形参都必须有默认值,例如在

上述代码中,如果给了a默认值,那么后面的b、c都得有默认值。

2、函数的声明和实现,两者间只能有一个带默认参数,否则,即使两者给的默认参数相同,也会产生

二义性,即编译器不知道选择声明的默认值还是实现的默认值。

二、占位参数

1、返回值类型 函数名(数据类型)
如果占位占位参数没有默认值,在调用时必须传入一个数据

2、占位参数可以有默认值

#include <iostream>
using namespace std;


int fun1(int a, int ) {
	cout << "123" << endl;
	return 0;
}
int fun2(int a, int =10) {
	cout << "456" << endl;
	return 0;
}
int main()
{
	fun1(10, 20);
	fun2(10);
	system("pause");
	return 0;
}

三、函数重载
两个函数使用相同的函数名

使用条件:相同的作用域;函数名称相同;函数参数的类型不同或个数不同或顺序不同。

1.参数个数不同

#include <iostream>
using namespace std;

void fun() {
	cout << "123" << endl;
}
void fun(int a) {
	cout << "456" << endl;
}
int main()
{
	fun();
	fun(10);
	system("pause");
	return 0;
}
输出:
123
456

2.参数类型不同

#include <iostream>
using namespace std;

void fun(double b) {
	cout << "123" << endl;
}
void fun(int a) {
	cout << "456" << endl;
}
int main()
{
	fun(2.3);
	fun(10);
	system("pause");
	return 0;
}
输出:
123
456

3.参数顺序不同

#include <iostream>
using namespace std;

void fun(int b,double a) {
	cout << "123" << endl;
}
void fun(double a,int b) {
	cout << "456" << endl;
}
int main()
{
	fun(10.9,20);
	fun(20,11.3);
	system("pause");
	return 0;
}
输出:
123
456

warning:
1、引用作为重载条件

#include <iostream>
using namespace std;

void fun(int &a) {	//int &a=10,不合法
	cout << "123" << endl;
}
void fun(const int &a) {	//const int &a=10,合法
	cout << "456" << endl;
}
int main()
{
	int a = 10;
	fun(a);
	fun(10);
	system("pause");
	return 0;
}
输出:
123
456

2、函数重载遇到默认参数
以下为一段错误代码,由使用了默认参数,导致了函数调用失败,所以,在使用函数重载时,不要使用默认参数

#include <iostream>
using namespace std;

void fun(int a,int b=10) {	//int &a=10,不合法
	cout << "123" << endl;
}
void fun(int a) {	//const int &a=10,合法
	cout << "456" << endl;
}
int main()
{
	int a = 10;
	//fun(10);//碰到默认参数,出现二义性,报错
	//fun(10,20);//不会报错,因为明显的参数个数不同
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值