函数提高
函數默認參數
#include <iostream> using namespace std;int func(int a, int b = 10, int c = 10) {return a + b + c; }//1. 如果某個位置參數有默認值,那么從這個位置往后,從左向右,必須都要有默認值 //2. 如果函數聲明有默認值,函數實現的時候就不能有默認參數 int func2(int a = 10, int b = 10); int func2(int a, int b) {return a + b; }int main() {cout << "ret = " << func(20, 20) << endl;cout << "ret = " << func(100) << endl;system("pause");return 0; }函數占位參數
C++中函數的形參列表里可以有占位參數,用來做占位,調用函數時必須填補該位置
#include <iostream> using namespace std; //函數占位參數 ,占位參數也可以有默認參數 void func(int a, int) {cout << "this is func" << endl; }int main() {func(10,10); //占位參數必須填補system("pause");return 0; }函數重載
函數重載概述
作用:函數名可以相同,提高復用性
函數重載滿足條件:
-
同一個作用域下
-
函數名稱相同
-
函數參數類型不同 或者 個數不同 或者 順序不同
注意: 函數的返回值不可以作為函數重載的條件
#include <iostream> using namespace std; //函數重載需要函數都在同一個作用域下 void func() {cout << "func 的調用!" << endl; } void func(int a) {cout << "func (int a) 的調用!" << endl; } void func(double a) {cout << "func (double a)的調用!" << endl; } void func(int a ,double b) {cout << "func (int a ,double b) 的調用!" << endl; } void func(double a ,int b) {cout << "func (double a ,int b)的調用!" << endl; }//函數返回值不可以作為函數重載條件 //int func(double a, int b) //{ // cout << "func (double a ,int b)的調用!" << endl; //}int main() {func();func(10);func(3.14);func(10,3.14);func(3.14 , 10);system("pause");return 0; }函數重載注意事項
-
引用作為重載條件
-
函數重載碰到函數默認參數
總結
- 上一篇: 内存分区模型
- 下一篇: 设计立方体类(求出立方体的面积和体积