如果下面的測試PROGRAMM爲什麼不明確的布爾()轉換的上下文轉換髮生
#include <iostream>
class A {
public:
A() {}
explicit operator bool() const {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return true;
}
// explicit operator bool() {
// std::cout << __PRETTY_FUNCTION__ << std::endl;
// return true;
// }
const operator int() const {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return 1;
}
operator int() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return 1;
}
};
int main() {
A a;
if (a) {
std::cout << "bool()" << std::endl;
}
if (a + 0) {
std::cout << "int()" << std::endl;
}
}
運行時,輸出爲
int A::operator int()
bool()
int A::operator int()
int()
,而不是
bool A::operator _Bool()
bool()
int A::operator int()
int()
我所期望的(以及如果取消評論部分的評論,你會得到什麼)。
所以問題是什麼規則將轉換爲非const-int優先轉換爲const-bool?
哪個編譯器? const操作符int()const'編譯失敗 –
編譯器是clang-3.4 – wimalopaan
你可以更新問題標題以刪除雙重否定。我會自己做,但我不確定是否刪除「不」或「不」。甚至兩個? – icabod