缺省参数&&函数重载

缺省参数:带有初始值的参数
注:1.非全缺省参数,参数的缺省值赋值要从最后边从右向左依次进行
eg:int Sum(int a,int b=1,int c=2);
2.实参的匹配是从左向右进行的
eg:int Sum(int a,int b=1,int c=2);
Sum(10,20);//10对应a,20对应b.
3.实参的入栈顺序是自右向左进行的

//全缺省参数:每个参数都带默认值

#include<iostream>
using namespace std;   //命名空间的包含

void Test(int a = 1, int b = 2, int c = 3) {
	cout << a << "  " << b << "  " << c << endl;
}
int main() {
	Test(100, 200, 300);
	Test(100, 200);
	Test(100);
	Test();
	system("pause");
	return 0;
}

函数重载:必须在相同的作用域,函数名字必须相同,参数列表必须不同
//重载条件
//参数列表必须不同:参数个数、参数类型

int Add(int left, int right)
{
	return left + right; 
}
double Add(double left, double right)
{
	return left + right;
}

int main() {
	Add(1, 2);
	Add(1.0, 2.0);
	Add('1', '2');
	system("pause");
	return 0;
}
void Test(int a) 
{}
void Test(char a)
{}
void Test(int a, char b)
{}
void Test(char a, int b)
{}
//跟大括号中有无返回值没有关系
int main() {
	Test(10);
	system("pause");
	return 0;
}

无参函数与单参函数同时存在,但单参函数不能带有缺省值
无参函数与同名的全缺省函数不能同时存在

void Test()
{}
void Test(int a = 10,int b = 20)
{}

int main() {
	Test(100);
	Test(); 
	system("pause");
	return 0;
}

注:此代码是无法正常运行的,因为无参函数与同名的全缺省函数存在于同一作用域。

C++编译器对函数名字修饰规则:将参数类型编译到函数名字中

int Add(int left, int right);

double Add(double left, double right);
//编译结果?Add@@YANNN@Z    Add@函数结束 @YA参数列表开始   int-H  double-N  @Z参数列表结束
int main() {
	Add(1, 2);
	Add(1.0, 2.0);
	Add('1', '2');
	system("pause");
	return 0;
}

//编译结果?Add@@YANNN@Z Add@函数结束 @YA参数列表开始 int-H double-N @Z参数列表结束

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值