C++函数进阶

函数默认参数:

在C++里,函数的形参是可以有默认值的

例:

#include <iostream>
using namespace std;

int func(int a,int b=20)
{
	return a+b;
}
int main()
{
	
	cout<<func(10)<<endl;
	return 0;
}

如果某个位置参数有默认值,那么从这个位置往后,从左往右,必须都要有默认值。

如果函数声明有默认值,调用时就不能有默认参数

函数占位参数:

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

例:


void func(int a, int) {
	cout << "this is func" << endl;
}

int main() {

	func(10,10); //占位参数必须填补

	system("pause");

	return 0;
}

函数重载:

在C++中,函数名可以相同,以便于提高复用性。

条件:

  • 在同一作用域下
  • 函数名相同
  • 函数参数类型或个数不同
  • 引用作为重载条件

例:

#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(int a ,double b)
{
	cout << "func (int a ,double b) 的调用!" << endl;
}
void func(double a ,int b)
{
	cout << "func (double a ,int b)的调用!" << endl;
}
void func(int &a)
{
	cout << "func (int &a) 调用 " << endl;
}

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



int main() {

	func();
	func(10);
	func(3.14);
	func(10,3.14);
	func(3.14,10);
	func(a); //调用无const
	func(10);//调用有const
    

	return 0;
}

函数返回值不可以作为函数重载条件
int func(double a, int b)
{
cout << “func (double a ,int b)的调用!” << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值