關於explicit 函式 形參型別轉換的疑惑
阿新 • • 發佈:2022-03-31
今日學習發現,
定義了一個testclass_explicit類,有如下建構函式 testclass_explicit(int data) :pridata(data){ cout << "pridata " << pridata << endl; }; testclass_explicit(char c) :prichar(c){ cout << "prichar " << c << endl; }; 再不新增explicit關鍵字的情況下,如下呼叫顯然正常 testclass_explicit t1(9);
testclass_explicit t2 = 67;
testclass_explicit t3('a');
testclass_explicit t4 = 'f';
輸出:
//pridata 9
// pridata 67
// prichar a
// prichar f
當對其中一個進行隱式抑制以後,explicit testclass_explicit(int data),我最開始想要的結果應該是int形參的隱式型別轉換被抑制,所以 testclass_explicit t2 = 67; 這句應當編譯報錯,
但實際上執行時呼叫了了char形參的建構函式,
輸出
//pridata 9
// prichar C //呼叫了了char形參的建構函式,
// prichar a
// prichar f
這裡我的疑問有兩個
一,為什麼最終去呼叫了char的建構函式,是因為對於int形參,剛好存在char形參函式,所以做了從int到char的型別匹配嗎,這看起來像是函式過載中的型別轉換,
二,那如何實現完全抑制形參為int的建構函式的隱式轉換呢
等改天看懂了再回來解答自己