缺省参数:带有初始值的参数
注: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参数列表结束