這篇文章主要介紹了C++缺省參數的概念是什么的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇C++缺省參數的概念是什么文章都會有所收獲,下面我們一起來看看吧。
缺省參數是聲明或定義函數時為函數的參數指定一個默認值。在調用該函數時,如果沒有指定實參則采用該默認值,否則使用指定的實參
#include<iostream> using namespace std; void TestFunc(int a = 0)//參數缺省值 { cout << a << endl; } int main() { TestFunc();//沒有指定實參,使用缺省值 TestFunc(10);//指定實參,使用實參 return 0; }
比如在 C 語言中有個很苦惱的問題是寫棧時,不知道要開多大的空間,之前我們是如果棧為空就先開 4 塊空間,之后再以 2 倍走,如果我們明確知道要很大的空間,那么這樣就只能一點一點的接近這塊空間,就太 low 了。但如果我們使用缺省,明確知道不需要太大時就使用默認的空間大小,明確知道要很大時再傳參
#include<iostream> using namespace std; namespace WD { struct Stack { int* a; int size; int capacity; }; } using namespace WD; void StackInit(struct Stack* ps) { ps->a = NULL; ps->capacity = 0; ps->size = 0; } void StackPush(struct Stack* ps, int x) { if(ps->size == ps->capacity) { //ps->capacity *= 2;//err ps->capacity == 0 ? 4 : ps->capacity * 2;//這里就必須寫一個三目 } } void StackInitCpp1(struct Stack* ps, int defaultCP) { ps->a = (int*)malloc(sizeof(int) * defaultCP); ps->capacity = 0; ps->size = defaultCP; } void StackInitCpp2(struct Stack* ps, int defaultCP = 4)//ok { ps->a = (int*)malloc(sizeof(int) * defaultCP); ps->capacity = 0; ps->size = defaultCP; } int main() { //假設明確知道這里至少需要100個數據到st1 struct Stack st1; StackInitCpp1(&st1, 100); //假設不知道st2里需要多少個數據 ———— 希望開小點 struct Stack st2; StackInitCpp2(&st1);//缺省 return 0; }
void TestFunc(int a = 10, int b = 20, int c = 30) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; cout << endl; } int main() { //非常靈活, TestFunc(); TestFunc(1); TestFunc(1, 2); TestFunc(1, 2, 3); //TestFunc(1, , 3);//err,注意它沒辦法實現b不傳,只傳a和b,也就是說編譯器只能按照順序傳 return 0; }
注意:
全缺省參數只支持順序傳參
//void TestFunc(int a, int b = 10, /*int f, - err*/ int c = 20);//err,void TestFunc(int a, int b = 10, /*int f, int x = y, -> err*/ int c = 20){cout << "a = " << a << endl;cout << "b = " << b << endl;cout << "c = " << c << endl;cout << endl;}int main(){//TestFunc();//err,至少得傳一個,這是根據形參有幾個非半缺省參數確定的TestFunc(1);TestFunc(1, 2);TestFunc(1, 2, 3);return 0;}//void TestFunc(int a, int b = 10, /*int f, - err*/ int c = 20);//err, void TestFunc(int a, int b = 10, /*int f, int x = y, -> err*/ int c = 20) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; cout << endl; } int main() { //TestFunc();//err,至少得傳一個,這是根據形參有幾個非半缺省參數確定的 TestFunc(1); TestFunc(1, 2); TestFunc(1, 2, 3); return 0; }
//a.hvoid TestFunc(int a = 10);//a.cppvoid TestFunc(int a = 20){}
注意:
半缺省參數必須從右往左依次來給出,且不能間隔著給
缺省參數不能在函數聲明和定義中同時出現
缺省值必須是常量或者全局變量
C 語言不支持缺省
關于“C++缺省參數的概念是什么”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“C++缺省參數的概念是什么”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。