函數的多載
可以省去對所有函數一一命名的麻煩
要如何使用它呢?
亦即使用同名稱
如果引數個數不同
或者引數個數相同 型態不同
函數就有不同功能
C++提供「多載」的功能
將功能相似的函數
以相同名稱命名
編譯器會根據引數的個數或形態
自動尋找最比配的函數使用
Ex:
編譯器會自動尋找適合的函數
不會吃掉小數點
[code language=”cpp”]
#include <iostream>
using namespace std;
int max(int,int);
double max(double,double);
int main(){
int a=5,b=10,max1;
max1=max(a,b);
cout << "a=" << a << " b=" << b << endl;
cout << "max=" << max1 << endl;
double c=1.456,d=6.4341,max2;
max2=max(c,d);
cout << "c=" << c << " d=" << d << endl;
cout << "max=" << max2 << endl; } int max(int a,int b){ if(a>b)
return a;
else
return b;
}
double max(double a,double b){
if(a>b)
return a;
else
return b;
}<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>
[/code]