重載函數
(1)定義:將一組功能非常相近的函數定義為重載函數。
(2)一組重載函數是以參數類型或參數個數加以區別的,只有傳回值不同不是一組重載函數,將會產生編譯錯誤。
(3)編譯器調用重載函數的規
#include <stdio.h>
void ShowMessage(const char* Text,int Type);
void ShowMessage(const char* Text,unsigned int Type);
int main()
{
unsigned char i=0;
ShowMessage("hello",i);
return 0;
}
void ShowMessage(const char* Text,int Type)
{
printf("Text=%s,Type=%d\n",Text,Type+1);
}
void ShowMessage(const char* Text,unsigned int Type)
{
printf("Text=%s,Type=%d\n",Text,Type);
}
輸出結果:Text=hello,Type=1
因為對參數個數相同的重載進行調用時,編譯器依次使用下面的規則將實參與形參進行匹配,確實重載函數的調用。
(1)具有與實參類型相同的形參的重載函數
(2)轉換實參,將T轉換成T&,或T&轉換為T,或T轉換為const T,然後尋找形參類型匹配的重載函數(T為某資料類型)
(3)實參進行標準的類型轉換,如char→int→unsigned int,然後尋找形參類型匹配的重載函數
(4)使用建構函式的轉換實參,使其與某一重載函數匹配。例如,如果類A有建構函式A(int),那麼int型轉換函式進行轉換,使其一重載函數匹配
(5)使用類型轉換函式進行轉換,使其與某一重載函數匹配
顯然,上述例子符合第3種情況。
再看下面例子:
#include <stdio.h>
void ShowMessage(const char* Text,const char* Caption);
void ShowMessage(const char* Text,unsigned int Type);
int main()
{
ShowMessage("hello",NULL); //NULL==0
return 0;
}
void ShowMessage(const char* Text,const char* Caption)
{
printf("Text=%s,Type=%s\n",Text,Caption);
}
void ShowMessage(const char* Text,unsigned int Type)
{
printf("Text=%s,Type=%d\n",Text,Type);
}
結果:會產生編譯錯誤 error C2668: 'ShowMessage' : ambiguous call to overloaded function
因為編譯器無法判斷第二個參數是Null 字元串NULL,還是整數0。所以,重載函數的定義和調用會涉及類型轉換的細節問題,在設計時要考慮全面。