gpt4 book ai didi

c++ - 编译器无法将显式转换应用于用作条件的表达式

转载 作者:搜寻专家 更新时间:2023-10-31 00:53:50 25 4
gpt4 key购买 nike

这是我的代码:

#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 时,代码可以正常工作。

然而,当我改变
显式运算符 int(){ return i; }
显式运算符 bool(){ return i != 0;

并将if(s == 4)分别修改为if(s),代码运行正常。

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

最佳答案

其中implicit conversions , 自 C++11 起,将为 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.

关于c++ - 编译器无法将显式转换应用于用作条件的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47446268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com