日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++中函數匹配機制詳解_C 語言

作者:__JAN__ ? 更新時間: 2022-04-16 編程語言

首先,編譯器會確定候選函數然后確定可行函數可行函數,再從可行函數中進一步挑選

候選函數:重載函數集中的函數

可行函數:可以調用的函數

最后進行尋找最佳匹配

有以下幾種規則

1.該函數的每個實參的匹配都不劣于其他可行函數

2.至少有一個實參的匹配優于其他可行函數的匹配

3.滿足上面兩種要求的函數有且只有一個

如果上面三個要求都沒滿足,則出現二義性

一些演示

各有一個精確匹配的實參,編譯器報錯,不滿足條件3

error

void func(int a,int b)
{
    cout << "(int,int)" << endl;
}
void func(double a, double b = 3.14)
{
    cout <<"(double,double = 3.14)" << endl;
}
int main()
{
    func(2.3,5);
}

調用函數類型轉換優先級,依次遞減

1.精確匹配

包含三種

(1)實參形參類型匹配

(2)從數組或者函數轉到對應的指針

(3)添加或者刪除頂層const

2.通過const轉換實現匹配

3.通過類型提升匹配

4.通過算術類型轉換或者指針轉換的匹配

5.通過類 類型轉換實現的匹配

小整形一般提升為int或者long,即便他的面量很小

void func(int a)
{
    cout << "(int)" << endl;
}
void func(short a)
{
    cout << "(short)" << endl;
}
int main()
{
    func(12);
    func('a');
}

?運行結果

所有算數類型級別轉換都一樣

error

void func(double a)
{
    cout << "(double)" << endl;
}
void func(float a)
{
    cout << "(float)" << endl;
}
int main()
{
    func(3.14);
}

不能重載const 和非const兩個版本,但是引用可以?

關于引用:非const可以升級為const,但是const不能降級為非const

若有兩種版本——const and not const,會根據傳入的參數自動匹配

void func(const int &a)
{
    cout << "(const int&)" << endl;   
}
void func(int &a)
{
    cout << "(int&)" << endl;
}
int main()
{
    const int a = 3;
    int b = 4;
    func(a);
    func(b);
    func(5);
}

運行結果

?指針的情況于引用類似:

如果兩個函數唯一的區別是他們指向的對象是常量或非常量,則編譯器根據實參選擇函數。

演示

void func(const int *a)
{
    cout << "(const int *)" << endl;
}
void func(int *)
{
    cout << "(int *)" << endl;
}
 
int main()
{
    int a = 3;
    int *pa = &a;
    const int *c_pa = &a;
    const int b = 4;
    const int *pb = &b;
    func(pa);
    func(c_pa);
    func(pb);
}

運行結果

?上面提到過的一些重載

using namespace std;
 
void func(int a)
{
    cout << "(int)" << endl;
}
void func(double a)
{
    cout << "(double)" << endl;
}
void func(int a,int b)
{
    cout << "(int,int)" << endl;
}
void func(double a, double b = 3.14)
{
    cout <<"(double,double = 3.14)" << endl;
}
void func(short a)
{
    cout << "(short)" << endl;
}
void func(float a)
{
    cout << "(float)" << endl;
}
void func(const int &a)
{
    cout << "(const int&)" << endl;
}
void func(int &a)
{
    cout << "(int&)" << endl;
}
void func(const int *a)
{
    cout << "(const int *)" << endl;
}
void func(int *)
{
    cout << "(int *)" << endl;
}

原文鏈接:https://blog.csdn.net/JAN6055/article/details/122841019

欄目分類
最近更新