1. 程式人生 > 資訊 >聯想小新 Pad Pro 12.6 將於 11 月 2 日釋出

聯想小新 Pad Pro 12.6 將於 11 月 2 日釋出

函式提高

函式預設引數

在C++中,函式的形參列表中的形參是可以有預設值的。

語法:返回值型別 函式名 (引數 = 預設值){ }

示例:

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++中函式的形參列表裡可以有佔位引數,用來做佔位,呼叫函式時必須填補該位置

語法:返回值型別 函式名 (資料型別){ }

示例:

//函式佔位引數,佔位引數也可以有預設引數
void func(int a,int){
    cout << "this is func" << endl;
}

int main(){
    func(10,10);//佔位引數必須填補
    
    system("pause");
}

函式過載

概述

作用:函式名可以相同,提高複用性

滿足條件

  • 同一個作用域下
  • 函式名相同
  • 函式引數型別不同或者個數不同或者順序不同

注意:函式的返回值不可以作為函式過載的條件

示例:

//函式過載需要在同一作用域下
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 main(){
    func();
    func(10);
    func(3.14);
    func(10,3.14);
    func(3.14,10);
    
    system("pause");
    return 0;
}

函式過載的注意事項

  • 引用作為過載條件

  • 函式過載碰到函式預設引數

//1.引用作為過載條件
void func(int &a){
    cout << "func(int &a)呼叫" << endl;
}
void func(const int &a){
    cout << "func(const int &a)呼叫" << endl;
}

//2.函式過載碰到函式預設引數
void func2(int a,int b = 10){
    cout << "func2(int a,int b = 10)呼叫" << endl;
}
void func2(int a){
    cout << "func2(int a)呼叫" << endl;
}

int main(){
    int a = 10;
    func(a); //呼叫無const
    func(10); //呼叫有const
    
    //func2(10); //碰到預設引數有歧義,需要避免
    
    system("pause");
    return 0;
}