gpt4 book ai didi

c++ - 强制值为 boolean 值 : (bool) makes warning, !!没有

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

我更喜欢 (bool),但它会生成警告。我如何摆脱警告?

我有这样的代码:

bool something_else = 0;

void switcher(int val = -1){
if(val != -1){
something_else = (bool)val;
}else{
something_else ^= 1;
}
}

我是否应该像其他人一样使用'!!'或者让它在使用 (bool) 时以某种方式隐藏警告消息?或者是'!!'实际上比 (bool) 快?

我想使用 (bool),所以我必须隐藏警告,但如何隐藏?

编辑:我用的是Visual Studio 2008,不好意思忘了说。

编辑 2: 警告消息是 warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning) 它出现了something_else = (bool)val;something_else = val; 但不在行 something_else = !!val;/p>

问题是,我希望它尊重我想将其转换为 boolean 值。我不想隐藏所有 boolean 警告,因为有时它们救了我的命。

最佳答案

您应该使用特定于 bool 类型的运算符和构造:

bool something_else = false;

void switcher(int val = -1)
{
if(val == -1) // val is -1 by default so THIS part is likely to execute
something_else = !something_else;
else
something_else = (val != 0);
}

如果您的昵称是不言自明的,那么编写其他人也能理解的代码可能是有意义的。对于这个特殊问题,适本地使用 bool 类型肯定会促进您与其他开发人员的进一步合作。

关于c++ - 强制值为 boolean 值 : (bool) makes warning, !!没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2439494/

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