C++——函數重載

來源:互聯網
上載者:User

標籤:style   real   names   bubuko   using   函數重載   turn   cout   分享圖片   

C++允許功能相近的函數在相同的範圍內以相同函數名聲明,從而形成重載,方便使用,便於記憶。

/*形參類型不同*/int add(int x,int y);float add(float x,float y);/*形參個數不同*/int add(int x,int y);int add(int x,int y,int z);

注意事項:

  >>重載函數的形參必須不同:個數不同或者類型不同

  >>編譯器將根據實參和形參的類型及個數的首選來選擇調用哪一個函數

/*編譯器不以形參名來區分*/int add(int x,int y);int add(int a,int b);/*編譯器不以傳回值來區分*/int add(int x,int y);void add(int x,int y);

  >>不要將不同功能的函式宣告為重載函數,以免出現調用結果的誤解,混淆。

int add(int x,int y){ return x +y;}float add(float x,float y){ return x - y;}

重載函數應用舉例:

  編寫兩個名為sumOfSquare的重載函數,分別求兩整數的平方和以及兩實數的平方和

#include<iostream>using namespace std;int sumOfSquare(int a, int b){    return a * a + b * b;}double sumOfSquare(double a, double b){    return a * a + b * b;}int main(){    int m, n;    cout << "Enter two integer: ";    cin >> m >> n;    cout << "Their sum of square: " << sumOfSquare(m, n) << endl;    double x, y;    cout << "Enter two real number: ";    cin >> x >> y;    cout << "Their sum of square: " << sumOfSquare(x, y) << endl;    system("pause");    return 0;}

輸出結果:

 

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.