2014-09-03 71 views
5

爲什麼CL實例到const int&的轉換在這裏曖昧?模糊轉換爲參考

struct CL 
{ 
    operator const int&() 
    { 
    } 
    operator int&() 
    { 
    } 
}; 

void fnc(const int&) 
{ 
} 

int main() 
{ 
    CL cl; 
    fnc(cl); 
} 

有兩種方式:
1)。 cl.operator const int&()導致用戶定義的轉換
2)。 cl.operator int&()導致用戶定義的轉換和資格轉換(0​​到const int&

第一種方式比第二種方式更好,不是嗎?我看到標準版,但什麼都沒發現。

回答

5

這是因爲在這種情況下,兩種轉換都適用(同樣好)。也就是說,int&const int&都可以綁定const int&

轉換不會含糊,如果你有:

void fnc(int&) 
{ 
}