標籤: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++——函數重載