wya*_*att 25 c++ boolean user-defined-types
使用所有基本类型的C++,可以简单地查询:
if(varname)
Run Code Online (Sandbox Code Playgroud)
并将类型转换为布尔值以进行评估.有没有办法在用户定义的类中复制此功能?我的一个类由一个整数标识,虽然它有许多其他成员,我希望能够以这种方式检查整数是否设置为NULL.
谢谢.
pla*_*ts1 37
C++ 11方法是:
struct Testable
{
explicit operator bool() const
{ return false; }
};
int main ()
{
Testable a, b;
if (a) { /* do something */ } // this is correct
if (a == b) { /* do something */ } // compiler error
}
Run Code Online (Sandbox Code Playgroud)
请注意explicit
阻止编译器隐式转换的关键字.
zvr*_*rba 23
您可以定义用户定义的转换运算符.这必须是成员函数,例如:
class MyClass {
operator int() const
{ return your_number; }
// other fields
};
Run Code Online (Sandbox Code Playgroud)
您还可以实现operator bool.但是,我强烈建议不要这样做,因为你的类可以在算术表达式中使用,这很快就会导致混乱.IOStreams定义,例如,转换为void*
.您可以void*
使用与测试a相同的方式进行测试bool
,但没有语言定义的隐式转换void*
.另一种选择是operator!
使用所需的语义进行定义.
简而言之:定义转换运算符sto整数类型(包括布尔值)是一个非常糟糕的主意.
只需operator bool()
为您的班级实施.
例如
class Foo
{
public:
Foo(int x) : m_x(x) { }
operator bool() const { return (0 != m_x); }
private:
int m_x;
}
Foo a(1);
if (a) { // evaluates true
// ...
}
Foo b(-1);
if (b) { // evaluates true
// ...
}
Foo c(0);
if (c) { // evaluates false
// ...
}
Run Code Online (Sandbox Code Playgroud)
正如其他人所说,使用operator int ()
oroperator bool ()
是个坏主意,因为它允许进行转换。使用指针是更好的主意。到目前为止,解决这个问题的最好方法是返回一个成员(函数)指针:
class MyClass {
void some_function () {}
typedef void (MyClass:: * safe_bool_type) ();
operator safe_bool_type () const
{ return cond ? &MyClass::some_function : 0; }
};
Run Code Online (Sandbox Code Playgroud)