C++学习笔记----函数高级

目录

5.1  函数默认参数

5.2  函数占位参数

5.3  函数重载


5.1  函数默认参数

        语法:返回类型 函数名(参数=默认值){}

        注意事项:

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

                如果函数的声明有默认参数,函数实现就不能有默认参数。(编译器不知道用哪个参数)

5.2  函数占位参数

        语法:返回类型 函数名(数据类型){}  //(括号里只写数据类型,传递的参数类型必须和所写的一样)

void test1(int a, int)
{
	cout << "func" << endl;

}
void test2(int a, int =10)//占位参数可以有默认参数
{
	cout << "func" << endl;

}

5.3  函数重载

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

        满足条件
               ①同一个作用域。(ex:都在全局作用域下)
               ②函数名称相同。
               ③参数类型不同/个数不同/顺序不同。

//在全局作用域
void test()
{
	cout << "调用test( )" << endl;
}
void test(int a) 
{
	cout << "调用test(int a)" << endl;
}
void test(double a)
{
	cout << "调用test(double a)" << endl;
}
void test(int a, int b)
{
	cout << "调用test(int a, int b)" << endl;
}
void test(int a, double b)
{
	cout << "调用test(int a, double b)" << endl;
}
void test(double a, int b)
{
	cout << "调用test(double a, int b)" << endl;
}
int main()
{
	test();
	test(10);
	test(3.14);
	test(10,3.14);
	test(3.14, 10);
	return 0;
}

        注意:函数的返回值不能作为函数重载的条件(返回值类型不同不行,有二义性)

        引用作为函数重载的条件

//引用作为重载条件
void test(int &a)
{
	cout << "调用test(int &a)" << endl;
}
void test(const int& b)
{
	cout << "调用test(const int& b)" << endl;
}
int main()
{
	int a = 10;
	const int b = 10;
	test(a);
	test(b);
    test(10); 
	return 0;
}

        函数重载碰到默认参数

//函数重载碰到默认参数
void test(int a,int b=10)
{
	cout << "调用test(int &a)" << endl;
}
void test(int a)
{
	cout << "调用test(const int& b)" << endl;
}
int main()
{
	test(10);//err,出现二义
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值