C++中函数高级主要有以下几点
1.函数默认参数
1) 函数是内有默认参数的,但是必须连续,即有n个参数的话,如果第i个有默认值,那么第i个到
第n个都必须有默认值 确定需要默认的参数,堆在最后几个就行了
2) 函数声明和函数定义只能有一个有默认参数
#include <iostream>
using namespace std;
int func(int a, int b, int c, int d=10)
{
return a + b + c + d;
}
int main()
{
cout<<func(10, 20, 30)<<endl;
cout << func(10, 20, 30, 40) << endl;
}
输出为70 100
2.函数占位参数
函数的参数可以只有类型名,没有实参,同时占位参数也可以有默认值
#include <iostream>
using namespace std;
void func(int a, int)
{
cout << "hahaha" << endl;
}
int main()
{
func(10,10);
}
输出为hahaha
3.函数重载
在C++中,函数是能够重载的,需满足下列条件
1)作用域相同
2) 函数名相同
3)参数的顺序,个数,类型不同
返回值不能作为重载条件,因为函数调用时只需要函数名和参数名,不需要返回值类型
#include <iostream>
using namespace std;
void func(int a, int)
{
cout << "hahaha" << endl;
}
int func(int a, double)
{
cout << "wawawa" << endl;
return 0;
}
int main()
{
//cout<<func(10, 20, 30)<<endl;
//cout << func(10, 20, 30, 40) << endl;
func(10, 10);
func(10, 1.00);
}
输出为 hahaha
wawawa
同样引用也可以作为重载条件,有无const是两个不同的类型
#include <iostream>
using namespace std;
void func(int &a)
{
cout << "hahaha" << endl;
}
int func(const int &a)
{
cout << "wawawa" << endl;
return 0;
}
int main()
{
//cout<<func(10, 20, 30)<<endl;
//cout << func(10, 20, 30, 40) << endl;
int a = 10;
func(a);
func(10);
}
输出同上
引用的实质时指针常量 int &a=a 是合法的 因为a有具体的内存
但是 int &a=10则不行 const int &a=10 是合法的 所以不具有二义性
最后 当函数有默认参数时最好不要重载,要重载的时候要确保不具有二义性,除默认参数外,其余参数也要满足重载的第三个条件
#include <iostream>
using namespace std;
void func(int a, int b, int c = 10)
{
cout << "hahaha" << endl;
}
void func(int a, int b)
{
cout << "wawawa" << endl;
}
int main()
{
//cout<<func(10, 20, 30)<<endl;
//cout << func(10, 20, 30, 40) << endl;
func(10,20,30);
}
当三个参数时,调用第一个函数没有异议,
但为两个参数时,就具有二义性了,编译器无法知道该调用哪一个函数