C++ 'overloading' if() 语句

C++ 'overloading' the if() statement

本文关键字:语句 overloading C++ if      更新时间:2023-10-16

是否有可能改变if()的行为,使:

class Foo {
    int x;
};
Foo foo;
if(foo)

仅在x的值不是零的情况下进行?还是…

将显式用户定义的类型转换为int是否可行?还是…

最好是做一些像if(foo.getX()) ?

您可以通过定义operator bool()将对象转换为布尔值:

explicit operator bool() const 
{ 
    return foo.getX(); 
}

explicit关键字阻止从Foobool的隐式转换。例如,如果您不小心将foo放入像foo + 1这样的算术表达式中,如果您将operator bool()声明为explicit,编译器可以检测到此错误,否则foo将被转换为bool,即使不是有意的。

通常形式的成员函数

operator TypeName()

(带有可选的explicitconst限定符)是转换操作符。它允许您将类强制转换为TypeName指定的任何类型。在另一个方向上,带一个参数的构造函数允许您将任何类型强制转换为类:

class Foo {
  Foo(int x);    // convert int to Foo
  operator bool() const;  // convert Foo to bool
  int x;
};

这为你的类定义了隐式转换。如果可能的话,编译器会尝试应用这些转换(就像它对内置数据类型所做的那样,例如5 + 1.0)。您可以将它们声明为explicit以抑制不需要的隐式转换。

可以定义一个操作符将对象转换为bool

class Foo
{
  int x;
public:
  operator bool() const
  {
    return x > 0;
  }
};

但是这可能会产生意想不到的后果,因为当您不希望进行转换时,会隐式转换到bool。例如

int x = 42 + Foo();

c++ 11通过允许您将转换操作符声明为explicit来解决这个问题,这样只允许在特定上下文中(例如在if语句中)进行隐式转换。

explicit operator bool() const // allowed in C++11
现在

int x = 42 + Foo();  // error, no implicit conversion to bool
int x = 42 + static_cast<bool>(Foo()); // OK, explicit conversion is allowed