0
点赞
收藏
分享

微信扫一扫

C++中函数的一些使用方法

天际孤狼 2022-03-11 阅读 114

1、函数的默认参数

在C++中,函数的参数是可以给默认值的,在使用函数时,没有传入的数据时,函数会使用默认参数,有传入的数据时,使用传入的数据。
语法:返回值类型 函数名(数据类型 形参名 = 默认值) {}
例:

#include<iostream>
using namespace std;

//函数默认参数

//如果有自己传入的数据,就用传入的数据,没有就用默认值

//函数的声明和实现只能有一个有默认值,不认会产生二义性
//int func(int a = 10, int b = 20, int c = 30);
//int func(int a, int b, int c);

int func(int a, int b=20, int c=30)
{
	return a + b + c;
}

int main()
{

	int a = func(10);
	cout << a << endl;

	system("pause");
	return EXIT_SUCCESS;
}

注意:
1、如果某个形式参数有了默认值,则这个形参后面的所有形参都要有默认值。
2、如果函数声明有默认参数,函数实现就不能有默认参数。

2、函数的占位参数

在C++中函数的形参列表里面可以有占位参数,用来占位。
语法:返回值类型 函数名(数据类型 形参, 数据类型) {}
例:

#include<iostream>
using namespace std;

//占位参数
void func(int a,int)
{
	cout << "this is function" << endl;
}

int main()
{
	func(10,10);

	system("pause");
	return EXIT_SUCCESS;
}

注意:在使用含有占位符的函数时,要填补占位符所在的数据。

3、函数的重载

函数重载的作用:函数名相同,通过传入的数据不同,来实现不同的功能,提高复用性。

函数重载使用时的条件:

  • 所有的函数必须在同一个作用域下
  • 重载函数的函数名称要相同
  • 函数参数的类型不同,或者个数不同,或者顺序不同

例:

#include<iostream>
using namespace std;

//函数重载,可以让函数名相同,提高复用性

void func()
{
	cout << "func的调用" << endl;
}

void func(int a)
{
	cout << "func(int a)的调用" << endl;
}

void func(double a)
{
	cout << "func(double a)的调用" << endl;
}

void func(double a, int b)
{
	cout << "func(double a,int b)的调用" << endl;
}

void func(int a, double b)
{
	cout << "func(int a, double b)的调用" << endl;
}
//函数的返回值不可以作为函数重载的条件
int main()
{
	func();
	int a = 1;
	func(a);

	func(1.1);

	func(1.1, 2);

	func(1, 1.2);

	system("pause");
	return EXIT_SUCCESS;
}

注意:

  • 函数的返回值不能作为函数重载的条件。
  • 在使用函数重载时,碰到函数带有默认参数,会产生二义性,程序报错。因此在使用函数重载时,最好不要加默认值。
举报

相关推荐

0 条评论