函数默认参数:
在C++里,函数的形参是可以有默认值的
例:
#include <iostream>
using namespace std;
int func(int a,int b=20)
{
return a+b;
}
int main()
{
cout<<func(10)<<endl;
return 0;
}
如果某个位置参数有默认值,那么从这个位置往后,从左往右,必须都要有默认值。
如果函数声明有默认值,调用时就不能有默认参数
函数占位参数:
C++中函数的形参列表里可以有占位参数,调用函数时必须填补该位置。
例:
void func(int a, int) {
cout << "this is func" << endl;
}
int main() {
func(10,10); //占位参数必须填补
system("pause");
return 0;
}
函数重载:
在C++中,函数名可以相同,以便于提高复用性。
条件:
- 在同一作用域下
- 函数名相同
- 函数参数类型或个数不同
- 引用作为重载条件
例:
#include <iostream>
using namespace std;
//函数重载需要函数都在同一个作用域下
void func()
{
cout << "func 的调用!" << endl;
}
void func(int a)
{
cout << "func (int a) 的调用!" << endl;
}
void func(double a)
{
cout << "func (double a)的调用!" << endl;
}
void func(int a ,double b)
{
cout << "func (int a ,double b) 的调用!" << endl;
}
void func(double a ,int b)
{
cout << "func (double a ,int b)的调用!" << endl;
}
void func(int &a)
{
cout << "func (int &a) 调用 " << endl;
}
void func(const int &a)
{
cout << "func (const int &a) 调用 " << endl;
}
int main() {
func();
func(10);
func(3.14);
func(10,3.14);
func(3.14,10);
func(a); //调用无const
func(10);//调用有const
return 0;
}
函数返回值不可以作为函数重载条件
int func(double a, int b)
{
cout << “func (double a ,int b)的调用!” << endl;
}