2

这是我的代码:

#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) 中,它说:

编译器将对用作条件的表达式应用显式转换

但是在这种情况下,没有这样的转换。当我删除explicit时,代码可以正常工作。

但是, 当我更改
explicit operator int(){ return i; }
explicit operator bool(){ return i != 0; }

并分别更改if(s == 4)if(s),然后代码工作正常。

看起来转换规则有点混乱,有人可以更详细地解释一下吗?

4

1 回答 1

4

隐式转换中,从 C++11 开始,将考虑显式用户定义的转换函数进行上下文转换;这发生在以下情况以及bool预期类型时。对于int,不适用。

在以下五个上下文中,bool如果声明 bool t(e); 则预期类型并构建隐式转换序列;格式良好。即显式的用户自定义转换函数,如显式 T::operator bool() const;被认为。据说这样的表达式 e 可以根据上下文转换为 bool。

controlling expression of if, while, for;
the logical operators !, && and ||;
the conditional operator ?:;
static_assert;
noexcept.
于 2017-11-23T01:32:06.233 回答