如何直接在布尔上下文中评估对象?

时间:2013-03-22 14:33:09

标签: c++ object boolean-expression

我想在布尔上下文中评估某个类的实例。或者更清楚一点,我想定义对象如果直接在布尔上下文中使用它会如何反应 这是一个例子:

class Foo 
{
  int state;
  Foo(): state(1) {}
  bool checkState()
  {
    return (state >= 0);
  }
  void doWork() 
  { 
    /*blah with state*/
  }
};

int main()
{
  Foo obj;
//while(obj.checkState())  //this works perfectly, and thats what i indent to do!
  while(obj)               //this is what want to write
    obj.doWork();
  return 0;
}

好的,它只是一个很好的:-),但这有可能吗?如果是,怎么样?

谢谢!

2 个答案:

答案 0 :(得分:11)

使用显式转换运算符bool:

explicit operator bool() const { return (state >= 0); }

完全你想要的:定义在布尔上下文中评估对象时会发生什么。

如果您有一个较旧的编译器,则不能使用explicit,这是不好的,因为operator bool()(没有explicit)最终可能会在非布尔上下文中被无意中使用。在这种情况下,请改用safe bool idiom

答案 1 :(得分:1)

您可以使用operator bool()

explicit operator bool() const
{
    return (state >=0) ;
}

如前所述,您希望使用explicit来防止在整数上下文中使用它。 main should return an int也是{{3}}。