c ++将类转换为boolean

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阻止编译器隐式转换的关键字.

  • 这应该是公认的最顶级的答案. (5认同)

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整数类型(包括布尔值)是一个非常糟糕的主意.

  • 在C++ 11中,有一个`显式运算符bool()`(在@plats中提到了答案和@UncleBens注释)实现了OP想要的东西.我认为如果将这些信息包含在已接受的答案中会很好. (6认同)
  • 1)OP显然不知道定义转换运算符的语法,否则他将能够编写最简单的解决方案.所以他学到了新东西.2)我警告他这是一个坏主意.3)安全bool更好,但看起来像过度工程.如果转换为void*对标准库有好处,那对我也有好处. (3认同)

Gar*_*ell 9

只需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)

  • C++ 0x有`显式运算符bool()`以避免那种隐式破坏? (4认同)
  • -1,这很容易以不明显的方式破坏.查看"安全布尔成语". (3认同)

wil*_*ilx 5

正如其他人所说,使用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)