C++学习笔记08,C++核心编程

//函数提高

1、函数默认参数

//C++中,函数的形参是可以有默认值的
//语法:返回值类型 函数名(参数=默认值){}

注意:
1、如果函数的某个位置已经有了默认参数,则从该位置往后,(从左到右),都必须有默认值
   即:int test07(int a, int b = 20, int c)	错误!!!	c必须有默认值
2、如果函数的声明有默认参数,函数实现不能有默认参数
int test07(int a, int b = 20, int c = 30)
{
	return a + b + c;
}
int main9()
{
	int ref;
	ref = test07(10, 20, 30);	//test07()的形参不设置默认值,则必须传入3个参数
	ref = test07(10);			//函数的形参设置默认值时,可以不用传入所有参数
	ref = test07(10, 30);		//主函数调用函数时,传入的参数能够覆盖所调用函数的形参的默认值

	cout << "ref = " << ref << endl;

	system("pause");
	return 0;
}

//思考:如果函数的形参都有默认值,想从第二个形参开始传值,如何写表达式?是否需要把第一个形参的默认值再传一遍???

2、函数占位参数

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

//void test08(int a, int = 10)	//占位参数也可以有默认参数,主函数调用时可以不用再传值
void test08(int a, int)
{
	cout << "Hello China" << endl;
}
int main10()
{
	test08(10, 10);	//第二个位置必须传入一个整型数据

	return 0;
}

3、函数重载

//作用:函数名可以相同,提高复用性

函数重载满足条件:
1、同一个作用域下(目前所写均为全局作用域)
2、函数名称相同
3、函数参数类型不同,或个数不同,或顺序不同
//注意:函数的返回值不可以作为函数重载的条件
3.1 概述
void test09(int a)
{
	cout << "test09(int a)的调用" << endl;
}
void test09(double b)
{
	cout << "test09(float b)的调用" << endl;
}
void test09(int a, float b)
{
	cout << "test09(int a, float b)的调用" << endl;
}
void test09(float a, int b)
{
	cout << "test09(float a, int b)的调用" << endl;
}
int main11()
{
	test09(10);
	test09(3.1415926);
	test09(10, 3.14);
	test09(3.14, 10);

	return 0;
}
3.2 函数重载注意事项
//1、引用作为重载条件
//2、函数重载碰到函数默认参数
//引用作为重载条件
void test10(int &a)//int &a = 10;不合法
{
	cout << "test10(int &a)的调用" << endl;
}
void test10(const int &a)//const int &a = 10;合法(相当于:int temp = 10; const int &a = temp;
{
	cout << "test10(const int &a)的调用" << endl;
}
//函数重载碰到函数默认参数
void test11(int a)
{
	cout << "test(int a)的调用" << endl;
}
void test11(int a, int b = 10)
{
	cout << "test(int a, int b = 10)的调用" << endl;
}
int main12()
{
	int a = 10;	
	test10(a);	//a 是局部变量,可读可写
	test10(10);	//10是全局常量,只读

	//test11(10);	//当函数重载碰到默认参数,存在二义性
	test11(10, 10);

	return 0;
}

(哔哩哔 哩黑马程序员 C++教程 学习笔记,如有侵权请联系删除)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值