编译器无法将显式转换应用于用作条件的表达式
compiler failed to apply explicit conversion to an expression used as a condition
这是我的代码:
#include <iostream>
using namespace std;
class Sales{
public:
Sales(int i = 0):i(i){}
explicit operator int(){ return i; }
private:
int i;
};
int main(){
Sales s(5);
if(s == 4) cout << "s == 4" << endl;
else cout << "s != 4" << endl;
return 0;
}
在c++ primer(5th)中,它说:
compiler will apply an explicit conversion to an
expression used as a condition
但在这种情况下,没有这种转换。
当我删除 explicit
时,代码可以正常工作。
然而,当我改变
explicit operator int(){ return i; }
至
explicit operator bool(){ return i != 0; }
、
并分别将 if(s == 4)
更改为 if(s)
,然后代码可以正常工作。
看起来转换规则有点混乱,有人可以更详细地解释一下吗?
在implicit conversions, since C++11, the explicit user-defined conversion function will be considered for contextual conversions之中;这发生在以下上下文中,并且需要类型 bool
时。对于 int
,它不适用。
In the following five contexts, the type bool
is expected and the
implicit conversion sequence is built if the declaration bool t(e); is
well-formed. that is, the explicit user-defined conversion function
such as explicit T::operator bool() const; is considered. Such
expression e is said to be contextually convertible to bool.
controlling expression of if, while, for;
the logical operators !, && and ||;
the conditional operator ?:;
static_assert;
noexcept.
这是我的代码:
#include <iostream>
using namespace std;
class Sales{
public:
Sales(int i = 0):i(i){}
explicit operator int(){ return i; }
private:
int i;
};
int main(){
Sales s(5);
if(s == 4) cout << "s == 4" << endl;
else cout << "s != 4" << endl;
return 0;
}
在c++ primer(5th)中,它说:
compiler will apply an explicit conversion to an expression used as a condition
但在这种情况下,没有这种转换。
当我删除 explicit
时,代码可以正常工作。
然而,当我改变
explicit operator int(){ return i; }
至
explicit operator bool(){ return i != 0; }
、
并分别将 if(s == 4)
更改为 if(s)
,然后代码可以正常工作。
看起来转换规则有点混乱,有人可以更详细地解释一下吗?
在implicit conversions, since C++11, the explicit user-defined conversion function will be considered for contextual conversions之中;这发生在以下上下文中,并且需要类型 bool
时。对于 int
,它不适用。
In the following five contexts, the type
bool
is expected and the implicit conversion sequence is built if the declaration bool t(e); is well-formed. that is, the explicit user-defined conversion function such as explicit T::operator bool() const; is considered. Such expression e is said to be contextually convertible to bool.controlling expression of if, while, for; the logical operators !, && and ||; the conditional operator ?:; static_assert; noexcept.