04-默認參數

寫在前面

聽說過函數有默認值嗎,想了一下,腦袋一團漿糊,好,今天來認識一下

名詞解釋

 C++允許函數設置默認參數,在調用時可以根據情況省略實參。規則如下:
 默認參數只能按照右到左的順序
 如果函數同時有聲明、實現,默認參數只能放在函數聲明中
 默認參數的值可以是常量、全局符號(全局變量、函數名)

碼上封口

將main.m 改爲mian.mm 文件
#include <iostream>
using namespace std;

void display(int a = 10, int b = 20) {
    cout << "a is " << a << endl;
    cout << "b is " << b << endl;
}

int main() {
    display();
    display(1);
    display(1,3);
}

看下打印結果:
a is 10
b is 20
a is 1
b is 20
a is 1
b is 3
是不是很厲害的樣子,嗯嗯,當時我也是這麼想的。

注意點

在文件裏是不是可以重載一下函數,定義兩個函數
void display(int a = 10) {
    cout << "a is " << a << endl;
}
void display() {
    cout << "display() " << endl;
}
此時會發現
display();
display(1);
這兩個函數調用會報錯"Call to 'display' is ambiguous",
這就是函數二義性,導致編譯器不知道調用哪一個,建議優先選擇使用默認參數。
可對比下第二講的函數重載部分。

完整代碼demo,請移步GitHub:DDGLearningCpp

當然C++大神就繞吧,非喜勿噴,畢竟這是個人的學習筆記📒

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章