C++——帶預設參數值的函數

來源:互聯網
上載者:User

標籤:str   主函數   set   man   cout   blog   結合   技術   height   

函數在聲明時可以預先給出預設的形參值,調用時如給出實參,則採用實參值,否則採用預先給出的預設參數值。

int add(int x = 5,int y = 6){ return x + y;}int main(){  add(10,20);//10+20  add(10);//10+6  add();//5 + 6          }

預設參數值的說明次序

有預設參數的形參必須在形參列表的最後,也就是說預設參數值的右面不能有無預設值的參數,因為調用時實參與形參的結合是從左至右的順序。

int add(int x,int y = 5,int z = 6);//正確int add(int x = 1,int y = 5,int z);//錯誤int add(int x = 1,int y,int z = 6);//錯誤

預設參數值與函數的調用位置

如果一個函數有原型聲明,並且原型聲明在定義之前,則預設參數值必須在函數原型聲明中給出;而如果只有函數的定義,或函數定義在前,則預設參數值需在函數定義中給出

#include<iostream>using namespace std;int add(int x = 5, int y = 6);int main(){    cout<<add();    system("pause");    return 0;}int add(int x, int y){    return x + y;}

結果為11

#include<iostream>using namespace std;int add(int x = 5, int y = 6){    return x + y;}int main(){    cout<<add();    system("pause");    return 0;}

結果相同

帶預設參數值的函數舉例:

計算長方體的體積:子函數getVolume是計算體積的函數,有三個形參:lengrh(長),width(寬),height(高),其中width和height帶有預設值

主函數中以不同形式調用getVoluime函數,剖析器的運行結果

#include<iostream>#include<iomanip>using namespace std;int getVolume(int length, int width = 2, int height = 3);int main(){    const int X = 10, Y = 12, Z = 15;    cout << "Some box data is ";    cout << getVolume(X,Y,Z) << endl;    cout << "Some box data is ";    cout << getVolume(X, Y) << endl;    cout << "Some box data is ";    cout << getVolume(X) << endl;    system("pause");    return 0;}int getVolume(int length, int width, int height){    cout << setw(5) << length << setw(5) << width << setw(5) << height << endl;    return length * width * height;}

輸出結果:

 

C++——帶預設參數值的函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.