gpt4 book ai didi

c++ - 显式转换运算符 bool

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:06 25 4
gpt4 key购买 nike

我有以下代码

  class C
{
public:
C(bool v_):v(v_){};
explicit operator bool() const {return v;}
bool v = false;
};

int main(){
C a{true};
C b{false};
// C d = true; // doesn't compile, since requires explicit conversion
C d = static_cast<bool>(true); // fine

if(a || b) std::cout << "conversion happened!" << std::endl; // why it doesn't require explicit conversion here?

}

它输出“转换发生了!”。我的问题是为什么 || 被认为是显式转换?

编辑

  // C d = true; // actually this line compiles because of the constructor

最佳答案

来自 [expr.log.or]:

The operands are both contextually converted to bool

允许上下文转换为 bool 以使用显式转换。这就是“上下文”概念的要点:在有意义的时候允许显式转换,否则就不允许,所以你不会不小心从 bool 转换中形成任意整数或指针值,但是当你实际要求一个 bool ,你明白了。

详情见 [conv]/4:

Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t

关于c++ - 显式转换运算符 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42613866/

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