3.1 函數默認參數
本節內容之前已經整理過,詳見22.函數的默認值
3.2 函數占位參數
C++中函數的形參列表里可以有占位參數,用來做占位,調用函數時必須補填該位置
語法:
返回值類型 函數名 (數據類型) {}
在現階段函數的占位參數存在意義不大,但是后面的課程中會用到該技術
示例:
#include <iostream>
using namespace std;// 函數占位參數,占位參數也可以有默認值
void func(int a, int) {cout << "this is a func" << endl;
}int main() {func(1, 2);return 0;
}
3.3 函數重載-基本語法
作用:函數名可以相同,提高復用性
函數重載滿足條件:
- 同一個作用域下
- 函數名相同
- 函數參數類型不同或者個數不同或者順序不同
注意:函數的返回值不可以作為函數重載的條件
示例:
#include <iostream>
#include <iostream>
using namespace std;// 1.參數類型不同
void print(int a)
{cout << "int" << endl;
}
void print(double a)
{cout << "double" << endl;
}// 2.參數順序不同
void print(double a, int b) {cout << "int int" << endl;
}
void print(int a, double b) {cout << "double double" << endl;
}
// 注意:同類型參數順序不同是不被允許的,因為函數名相同,編譯器會認為這是同一個函數
// void print(int a, int b) {}和void print(int b, int a) {}同時出現時,編譯器會報錯// 3。參數個數不同
void print(int a, int b, int c) {cout << "int int int" << endl;
}
void print(int a, int b, int c, int d) {cout << "int int" << endl;
}// 注意事項:函數返回值類型不同不可作為函數重載的條件
int main()
{print(1);print(1.0);print(1.0, 1);print(1, 1.0);print(1, 1, 1);print(1, 1, 1, 1);return 0;
}
3.4 函數重載-注意事項
- 引用作為重載條件
- 函數重載碰到函數默認參數
示例:
#include <iostream>
using namespace std;// 函數重載注意事項
// 1.引用作為重載的條件
void fun(int& a) {cout << "func(int& a)調用" << endl;
}void fun(const int& a) {cout << "func(const int& a)調用" << endl;
}// 2.函數重載碰到默認參數
void func(int a) {cout << "func(int a)調用" << endl;
}
void func(int a, int b = 10) {cout << "func(int a, int b = 10)調用" << endl;
}int main() {// func(int& a)調用int a = 10;fun(a);// func(const int& a)調用const int b = 10;fun(b);fun(10);// 當函數調用碰到默認參數會出現二義性報錯// func(10); // 錯誤?,默認參數不能省略func(10,10); // 正確return 0;
}