C++之函數重載

來源:互聯網
上載者:User

重載函數

(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。所以,重載函數的定義和調用會涉及類型轉換的細節問題,在設計時要考慮全面。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.