函数
1.函数默认参数
在c++中,函数的形参列表中的形参可以有默认值
语法:返回值类型 函数名 (参数=默认值){}
注意:
1.如果某位置有默认参数,则该位置以后都必有默认值
2.若函数声明有默认,函数实现就不能有默认参数
2.函数占位参数
c++中函数的形参列表里可以有占位参数,调用时必须填补该位置
语法:返回值类型 函数名(数据类型){}
3.函数重载
3.1函数重载概述
作用:函数名可以相同,提高复用性
条件:
同一作用域下
函数名称相同
函数参数类型不同或者个数不同或者顺序不同
注意:函数返回值不可作为函数重载条件
示例:
#include <iostream>
using namespace std;
int func(){
cout<<"func()的调用!"<<endl;
return 0;
}
int func(double a){
cout<<"func(double)的调用!"<<endl;
return 1;
}
int func(int a,double b){
cout<<"func(int a,double b)的调用!"<<endl;
return 2;
}
int func(double b,int a){
cout<<"func(double b,int a)的调用!"<<endl;
return 3;
}
int main(){
func();
func(3.14);
func(1,3.14);
func(6.28,2);
return 0;
}
3.2函数重载注意事项
引用作为重载条件
#include <iostream>
using namespace std;
void print(const int & ref){
cout<<"print(const int & ref)调用"<<endl;
}
void print(int & ref){
cout<<"print(int & ref)调用"<<endl;
}
int main(){
int a=10;
print(a);
print(10); //传入10时,由于 int &ref=10; 语句非法,故不会调用print(int & ref)
return 0;
}
函数重载碰到函数默认参数
#include <iostream>
using namespace std;
void print2(int a,int b=1){
cout<<"print2(int a, int b)调用"<<endl;
}
void print2(int a){
cout<<"print2(int a)调用"<<endl;
}
int main(){
print2(10); //词句出现为非法,因为两个函数都满足调用条件
print2(10,20); //此句将合法调用print2(int a, int b)
return 0;
}