本篇內容主要講解“什么是C++默認參數”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“什么是C++默認參數”吧!
通常情況下,函數在調用時,形參從實參那里取得值。對于多次調用同一函數同一實參時,C++給出了更簡單的處理辦法。給形參以默認值,這樣就不用從實參那里取值了。
#include <iostream> #include <ctime> using namespace std; void weatherForcast(char * w="sunny") { time_t t = time(0); char tmp[64]; strftime(tmp,sizeof(tmp), "%Y/%m/%d %X %A ",localtime(&t) ); cout<<tmp<< "today is weahter "<<w<<endl; } int main() { //sunny windy cloudy foggy rainy weatherForcast(); weatherForcast("rainny"); weatherForcast(); return 0; }
#include <iostream> using namespace std; float volume(float length, float weight = 4,float high = 5) { return length*weight*high; } int main() { float v = volume(10); float v1 = volume(10,20); float v2 = volume(10,20,30); cout<<v<<endl; cout<<v1<<endl; cout<<v2<<endl; return 0; }
1.規定默認參數必須從函數參數的右邊向左邊使用
正確聲明: void fun1(int a, int b=10); void fun2(int a, int b=10, int c=20); 錯誤聲明: void fun3(int a=5, int b, int c); void fun4(int a, int b=5, int c);
2.默認參數不能在聲明和定義中同時出現
錯誤 聲明: void fun1(int a=10); 定義: void fun1(int a=10){......} 正確 聲明: void fun2(int a=10); 定義: void fun2(int a){......} 或者 聲明: void fun2(int a); 定義: void fun2(int a=10){......}
3.函數聲明和定義一體時,默認參數在定義或聲明處都可以。聲明在前,定義在后的話,默認參數在聲明處
4.一個函數,不能又作重載,又作默認參數的函數。當你少寫一個參數時,系統無法確認時重載還是默認函數。
void print(int a) { } void print(int a,int b =10) { } int main() { print(10); return 0; } error:main.cpp:14: error: call of overloaded 'print(int)' is ambiguous print(10);
到此,相信大家對“什么是C++默認參數”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。