首页 > 编程语言 > 详细

c++--函数重载

时间:2021-06-12 17:43:44      阅读:27      评论:0      收藏:0      [点我收藏+]

函数高级

1.函数的默认参数

//1.形参可以有默认参数
int fun(int a,int b=10)
{
    return a+b;
};
//如果某个位置有默认参数,从该位置往后都要有默认值
//int fun(int a=10,int b) 错误
//2.函数声明时有默认值,实现时就不能有默认参数
//int fun(int a,int b=10);错误

2.占位参数

占位参数用来占位 调用时需要填补该位置

void fun(int a,int)
{
    cout<<" ***"<<endl;
}
//占位参数可以有默认参数
int main()
{
    fun(10,20)//函数调用
    
    
    system("pause");
    return 0;
}

3.函数重载

3.1函数重载条件

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

重载条件:

  • 1.同一个作用域下
  • 2.函数名称相同
  • 3.函数参数类型不同,或者个数不同,或者顺序不同
int fun(int a, int b)
{
	return a + b;
}
//返回值不可以做函数重载的条件
//void fun(int a, int b)
//{
//	cout << a + b << endl;
//}

double fun(double b, double a)
{
	return a + b;
}
int main()
{
	cout << fun(12.12, 12.12) << endl;
	cout << fun(12, 12) << endl;

	system("pause");
	return 0;
}

3.2函数重载注意事项

//函数重载注意事项
//引用作为函数重载条件
void fun(int &a)
{
	cout<<"void fun(int a)"<<endl;
}
void fun(const int &a)
{
	cout << "void fun(const int& a)" << endl;
}
//函数重载碰到默认参数
void fun1(int a,int b=10)
{
	cout << "void fun(int a,int b)" << endl;
}
void fun1(int a)
{
	cout << "void fun(const int& a)" << endl;
}
int main()
{
	int a = 10;
	fun(a);
	fun(10);
	fun1(a,20);
	//fun1(20); 默认参数 两个重载
	system("pause");
	return 0;
}

c++--函数重载

原文:https://www.cnblogs.com/panq/p/14878403.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!