? ? ?什么是函数的默认参数
? ? ? 在c++中,函数的形参是可以有默认值的
语法:返回类型? 函数名 (参数=默认值){}
我们来看一个例子:
问:以下程序的输出结果为多少????
?
2.函数的占位参数
什么是占位参数,先来举个列子
比如你在图书馆学习,突然肚子疼,要上厕所,那么你应该放一本书,或者放电脑在你的位置上,占着你的座位,不然你上完回来就被其他同学坐着了。
函数也是一样:
C++中函数的形参列表里面可以有占位参数,用来占位,调用函数时必须补该位置
语法:返回值类型? ?函数名? ? (数据类型){}
3.函数重载
作用:函数名可以相同,提高函数的复用性,根据函数中的参数不同来调用不同的函数。
函数重载的满足条件:
1.同一个作用域下
2.函数名相同
3.参数类型不同,数量不同,顺序不同
在同一个作用域下、函数名相同、参数数量不同!
void func() {
cout<<"你好"<<endl;
}
void func(int a) {
cout<<"Hello"<<endl;
}
int main() {
func(5);
system("pause");
return 0;
}
在同一个作用域下、函数名相同、参数类型不同!
void func(double a) {
cout<<"你好"<<endl;
}
void func(int a) {
cout<<"Hello"<<endl;
}
int main() {
func(5);
system("pause");
return 0;
}
?
在同一个作用域下、函数名相同、参数顺序不同!
?
void func(double a,int b) {
cout<<"你好"<<endl;
}
void func(int a,double b) {
cout<<"Hello"<<endl;
}
int main() {
func(5,3.14);
system("pause");
return 0;
}
3.1函数重载的注意事项
1.引用作为重载条件
2.函数重载碰到默认参数
我们直接来看代码:
void func(int &a) {
cout<<"你好"<<endl;
}
void func(const int &a) {
cout << "Hello" << endl;
}
int main() {
func(2);
system("pause");
return 0;
}
void func(int &a) {
cout<<"你好"<<endl;
}
void func(const int &a) {
cout << "Hello" << endl;
}
int main() {
int a = 10;
func(a);
system("pause");
return 0;
}
?
void func(int a,int b) {
cout<<"你好"<<endl;
}
void func( int a) {
cout << "Hello" << endl;
}
int main() {
func(2);
system("pause");
return 0;
}
void func(int a,int b=10) {
cout<<"你好"<<endl;
}
void func( int a) {
cout << "Hello" << endl;
}
int main() {
func(2);
system("pause");
return 0;
}
当函数重载碰到了默认参数 ? 编译器傻了 ? 又能调用上面的func 又能调用下面的func? ,所以我们要尽量避免写出这样的代码。
?
原文:https://blog.51cto.com/u_15100290/2887676