c ++将类转换为布尔值

2022-01-19 00:00:00 boolean c++ user-defined-types

对于 C++ 的所有基本类型,可以简单地查询:

With all of the fundamental types of C++, one can simply query:

if(varname)

并且类型被转换为布尔值以进行评估.有没有办法在用户定义的类中复制这个功能?我的一个类由一个整数标识,尽管它有许多其他成员,我希望能够检查整数是否以这种方式设置为 NULL.

and the type is converted to a boolean for evaluation. Is there any way to replicate this functionality in a user-defined class? One of my classes is identified by an integer, although it has a number of other members, and I'd like to be able to check if the integer is set to NULL in such a manner.

谢谢.

推荐答案

您可以定义一个用户定义的转换运算符.这必须是成员函数,例如:

You can define a user-defined conversion operator. This must be a member function, e.g.:

class MyClass {
  operator int() const
  { return your_number; }
  // other fields
};

您还可以实现运算符 bool.但是,我会强烈建议不要这样做,因为您的课程将变得可用于算术表达式,这会很快导致混乱.例如,IOStream 定义转换为 void*.您可以像测试 bool 一样测试 void*,但没有来自 void* 的语言定义的隐式转换.另一种选择是使用所需的语义定义 operator!.

You can also implement operator bool. However, I would STRONGLY suggest against doing it because your class will become usable in arithmetic expressions which can quickly lead to a mess. IOStreams define, for example, conversion to void*. You can test void* in the same way you can test a bool, but there are no language-defined implicit conversions from void*. Another alternative is to define operator! with the desired semantics.

简而言之:定义转换运算符 sto 整数类型(包括布尔值)是一个非常糟糕的主意.

In short: defining conversion operator sto integer types (including booleans) is a REALLY bad idea.

相关文章