【问题标题】:Why warning "forcing value to bool 'true' or 'false'" disappears when using not operator?为什么在使用 not 运算符时警告“强制值为 bool 'true' 或 'false'”消失?
【发布时间】:2016-07-21 16:00:05
【问题描述】:

考虑使用 Visual Studio 2015 编译的以下代码:

#include <iostream>
#include <cassert>

void foo( bool b )
{
    std::cout << b;
}

int main()
{
    int a;

    foo( a = 2 );       // getting warning #4800
    foo( !(a = 2) );    // not getting any warning

    return 0;
}

foo( a = 2 ) 产生警告 4800 'int': forcing value to bool 'true' or 'false',很好。

foo( !(a = 2) ) 不会产生警告。为什么?在某些时候,有一个 int 到 bool 转换!

【问题讨论】:

  • 编译器不保证会向您发出任何警告。彻底的 C++ 错误,是的,警告,不是。

标签: c++ warnings


【解决方案1】:

foo(a = 2) 等价于bool b = (a = 2)。表达式a = 2 返回一个a,所以它等价于

a = 2;
bool b = a; //Conversion of 'int' to 'bool' -> Warning!

foo(!(a = 2)) 等价于bool b = !(a = 2)。表达式a = 2 返回a

a = 2;
bool b = !a; //'!a' is legal => It returns a bool -> No warning!

请注意,您可以将operator! 应用于int,这会否定int,因此返回bool。这就是没有性能警告的原因。

【讨论】:

  • 这都是正确的,但它没有回答问题。
  • @PeteBecker 你能解释一下为什么吗?我是不是误会了什么?
  • @Rakete1111:您可能需要添加 ! int 进行操作(即,不进行强制转换)并且仍然返回 bool..
  • @lorro 我已经写过了,最后一段。是不是还不够清楚?
  • @Rakete1111:当你说“转换”时,人们可能会认为这是一个演员表。 VSCPP 中从intbool 的演员表触发了这个(恕我直言完全没有意义)警告。 bool operator!(int) 对用户隐藏此“转换”。小事我同意,只是为了确保没有人认为! 应该触发这个警告。
猜你喜欢
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 2011-02-09
  • 2013-06-13
  • 2015-10-03
相关资源
最近更新 更多