gpt4 book ai didi

c++ - C++ 中将内置类型 (int) 转换为 bool 的首选方法是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:45 26 4
gpt4 key购买 nike

用Visual C++编程时,我想每个开发者都习惯于看到警告

warning C4800: 'BOOL' : forcing value to bool 'true' or 'false'

不时。原因显然是 BOOL 被定义为 int 并且直接将任何内置数值类型分配给 bool 被认为是一个坏主意。

所以我现在的问题是,给定任何要解释为 boolean 值的内置数字类型(int、short、...),将这个值实际存储到变量中的/您的首选方式是什么类型 bool?

注意:虽然混合使用 BOOL 和 bool 可能不是一个好主意,但我认为无论是在 Windows 还是其他地方,这个问题都不可避免地会出现,所以我认为这个问题既不是 Visual-C++ 也不是 Windows 特定的。

给定 int nBoolean; 我更喜欢这种风格:

  • bool b = nBoolean?true:false;

以下可能是备选方案:

  • bool b = !!nBoolean;

  • bool b = (nBoolean != 0);

是否有普遍首选的方式?理由?

我应该补充:因为我只使用 Visual-C++,所以我不能确定这是一个 VC++ 特定的问题,还是其他编译器也会出现同样的问题。因此,专门听听 g++ 或用户如何处理 int->bool 情况会很有趣。

关于标准 C++:正如 David Thornley 在评论中指出的那样,C++ 标准不需要这种行为。事实上,它似乎明确允许这样做,所以人们可能会认为这是 VC++ 的怪癖。引用 N3029 草稿(这是我在 atm 周围的草稿):

4.12 Boolean conversions [conv.bool]

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. (...)

最佳答案

在使用win32 SDK和MFC的情况下,我倾向于这样写。这是明确的。

bool b = (myBOOL != FALSE);

编辑:我已经编辑了 :-) 因为我不确定 myBOOL == TRUE 是否适用于 BOOL 的所有实现并且我可以假设 FALSE 在大多数情况下可能具有 0 值。

关于c++ - C++ 中将内置类型 (int) 转换为 bool 的首选方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4852249/

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