函数提高

函数的提高(默认参数,占位符合重载)

函数默认参数

在C++中,函数的形参列表中的形参是可以有默认值的。当调用函数时,可以如果没有传入参数,函数就会用它的默认形参 。
语法:返回值类型 函数名 (参数=默认值){ }

例子:


int func01(int a, int b = 100, int c = 90)
{
	return a + b + c;
}


int func02(int a = 10, int b = 90);
int func02(int a , int b)
{
	return a + b;
}

void test01()
{
	//1. 如果某个位置参数有默认值,那么从这个位置往后,从左向右,必须都要有默认值
	//2. 如果函数声明有默认值,函数实现的时候就不能有默认参数
	cout << "ret01=" << func01(10) << endl;
	cout << "ret02=" << func02() << endl;
}

int main()
{
	test01();

	system("pause");
	return 0;
}

函数占位操作

C++中函数的形参里可以有占位参数,用来做占位,调用函数时必须要填补该位置
语法:返回值类型 函数名 (数据类型){}

例子:

void func03(int a,int )
{
	cout << "this is a function" << endl;
}
int test02()
{
	func03(10,1);
}

函数的重载

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

满足的条件:

  • 同一个作用域
  • 函数的名称相同
  • 函数的参数类型不同或者个数和顺序不同

LOOK! 函数的返回值不可以作为函数重载的条件


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

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

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

}


void test04()
{

	func04(10.0, 10);

}

int main()
{
	test04();

	system("pause");
	return 0;
}

函数返回值不可以作为函数重载条件

//函数返回值不可以作为函数重载条件
int  funco4(double a, int b)
{
	cout << "func04_(double a ,int b)的调用!" << endl;
	return 0;
}

void test04()
{
	int a = func04(10.0, 10);
	cout<<a<<endl;

}

在这里插入图片描述
函数重载的注意事项:

  • 引用作为重载条件
  • 函数重载碰到函数的默认参数

1.引用作为重载条件


//1、引用作为重载条件

void func04(int& a)//int &a =10;//不合法,因为10 是个常量在常量区,而应该引用在栈区或者堆区
{
	cout << "func04(int &a)调用" << endl;
}

void func04(const int &a)
{
	cout << "func04(const int &a)调用" << endl;
}
/*
加入const就可以了,编译器优化代码,
int temp = 10; const int& a = temp;*/



func04(10);//调用有const

上面会调用有const的函数,因为如果是无const,不合法,因为10 是个常量在常量区,而应该引用在栈区或者堆区。加入const就可以了,编译器优化代码,int temp = 10; const int& a = temp;

2、函数重载碰到函数默认参数

void func05(int a, int b = 10)
{
	cout << "fun05(int a, int b = 10) 调用" << endl;
}

void func05(int a)
{
	cout << "func05(int a) 调用" << endl;
}
func05(10); //碰到默认参数产生歧义,需要避免

上面的代码将会出现问题,因为传入10时就会产生歧义,无论传到那个函数中,都是可以的,所以产生了歧义。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值