C ++类转换为布尔
与所有的基本类型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
};
您也可以实现运营商布尔。不过,我的强烈建议反对这样做,因为你的类将成为算术前pressions可迅速导致一个烂摊子使用。输入输出流定义,例如,转换为无效*
。您可以在您可以测试布尔
,但没有语言的定义隐式转换同样的方式测试无效*
从无效*
。另一种方法是定义运营商!
与所需的语义。
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.