標籤:

C++ 隱式類型轉換重載決議的具體優先順序是怎樣的?

最近在看 @陳碩 老師評註的 c++ primer,看到 p363 的一段評註不是很理解

#include &
using std::cout;
using std::endl;
using std::string;

class Test {
public:
void find(const string first_name, const string last_name);
void find(const string name, bool retied);
};

void Test::find(const string first_name, const string last_name)
{
cout &<&< "find 1" &<&< endl; } void Test::find(const string name, bool retied) { cout &<&< "find 2" &<&< endl; } int main() { Test *t = new Test(); t-&>find("shuo", "chen");
return 0;
}

這兩個方法都有隱式轉換

1. 字面字元串轉換為 string

2. 字面字元串轉換為 bool

為何在以上代碼裡面會選在 2 的決議呢?


我記得C++重載函數的匹配分四個優先順序:

直接匹配&>類型提升轉換(float-&>double這種)&>隱式轉換&>類類型轉換。

單個實參調用的非explicit構造函數,決定一個類類型轉換。

指針轉換為bool是隱式轉換。


C++11中規定了自定義類型的轉換髮生在標準轉換序列之後(p81)。下圖是標準轉換序列的完整列表(p304),可以看到有boolean轉換,即任意數值、枚舉或指針轉換成bool。而轉換成std::string是自定義類型轉換,只在標準轉換序列無法嚴格匹配的時候才會適用。


簡化一下:
void foo(const string name);
void foo(bool on);

foo("C++"); // 調用哪個?這個不難推斷吧?


推薦閱讀:

C++如何調用matlab庫函數?
Clang 解析錯誤和報錯的機制?
C++ std::set 的實現中對於iterator的這個強制轉換是如何進行的?
C++中的鏈表怎樣逆序輸出?

TAG:C | CPrimer |