函数默认参数:
- 语法: 返回值类型 函数名 (形参 = 默认值){ }
- 如果自己传入数据,就用传入的数据,如果没有(那么用默认值)。
- 传入数据 依次对应默认值
- 如果某个位置已经有了默认参数,那么从这个位置往后,从左到右必须有默认值
- 如果函数声明由默认参数,函数实现就不能有默认参数(声明和实现只能有一个默认参数)。
int swap03(int a=10,int b=20); //函数声明 int swap03(int a=10,int b=20) //函数实现 : 这会报错的 { return a+b; } //正确写法应该是 int swap03(int a,int b) //函数实现 { return a+b; }
#include<iostream> using namespace std; int swap(int a =10,int b=20,int c = 30) //都设有默认值 { return a + b + c; } int swap2(int a=1,int b,int c) //会报错:默认实参不在形参列表的结尾 { return a+b+c; } int main() { int a = 10; swap(); //不输入参数,用默认值 cout << "调用函数第一次: " << swap() << endl; swap(20, 30); //自己输入参数 cout << "调用函数第二次: " << swap(20, 30) << endl; }
函数占位参数:
作用:?后面的内容会涉及到
c++中函数的形参列表里可以有占位参数,
用来做占位,调用函数时必须填补该位置。
语法:返回值类型 函数名 (数据类型) { }#include<iostream> using namespace std; //第一种写法:void func(int a, int) void func(int a,int = 10) //可以有默认参数 { cout << "this is func" << endl; } int main() { func(10, 10); //占位参数必须填补 //func(10); 第一种写法时不合法 }
函数重载的基本语法:
作用:函数名可以相同,提高复用性
函数重载满足条件:
同一个作用域下
函数名称相同
函数参数类型不同 或者个数不同 或者顺序不同#include<iostream> using namespace std; //第一个函数 void func() { cout << "func()的调用" << endl; } //第二个函数 void func(int a) { cout << "func(int)的调用" << endl; } int main() { func(100); //调用第二个函数 func(); //由于参数个数不同 调用第一个函数 }
注意:函数的返回值类型 不可以作为函数重载的条件
比如两个函数 void func(int a,int b) int func(int a,int b)不可以看做函数重载
在(参数个数,参数类型都相同)都相同的情况下,两者只是类型不同,不能看做函数重载
函数重载的注意事项:
引用作为函数重载的条件:
关键在于 传入的参数能不能改变(是不是可读可写)
#include<iostream> using namespace std; //引用作为函数重载的条件 void func(int& a) { cout << "func(int& a)调用" << endl; } void func(const int& a) { cout << "func(const int& a)调用" << endl; } int main() { int a = 10; func(a); //会运行第一个 ,因为int& a 可读可写 const int b = 10; //会调用第一个,因为第一个可读可写 func(b);//调用第二个,因为只读不可写 //或者只传入值,会调用第二个 func(10); //因为第二个函数的形参类型是常量引用 }
使用函数重载时使用默认参数会报错,产生二义性(所以要尽量避免)