【问题标题】:C++ 'overloading' the if() statementC ++“重载” if() 语句
【发布时间】:2013-05-02 03:57:52
【问题描述】:

是否可以更改if() 的行为,以便:

class Foo {
    int x;
};

Foo foo;
if(foo)

仅当x 的值不是零时才继续?或者...

将用户定义的显式类型转换为 int 工作/这是一种合适的方法吗?或者...

最好做if(foo.getX())之类的事情吗?

【问题讨论】:

标签: c++ if-statement operator-overloading type-conversion


【解决方案1】:

您可以通过定义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 以抑制不需要的隐式转换。

【讨论】:

  • 明确表示可能更好。
  • 肯定想要明确地标记这个,除非你想让人们做像!myClass这样的事情。
【解决方案2】:

您可以定义一个运算符将对象转换为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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多