5

The modern versions of C++ attempt to use the bool operator of a class when evaluating the condition in an if() statement. Other casting operators, such as int being use when no bool operator exists. This is demonstrated below.

#include <iostream>
using namespace std;

class TwoInts {
  public:
    int a,b;
    operator bool() { cout << "TwoInts to bool" << endl; return 0;}
    operator int()  { cout << "TwoInts to int"  << endl; return 0;}
};

class SixInts {
  public:
    int a[6];
    operator int()  { cout << "SixInts to int" << endl; return 0;}
};

int main(void) {
  TwoInts T;
  SixInts S;
  if (T) cout << "xxx" << endl;
  if (S) cout << "xxx" << endl;
  return 0;
}

Running this code produces no surprises:

TwoInts to bool
SixInts to int

Looking over some old C++ code, there appears to be a change that I would like to verify.
Did older versions of C++ use the int operator of a class when evaluating the condition in an if() statement? What versions, if any, did that?

The suggested output then would have been

TwoInts to int
SixInts to int

Some details as to why the question: Issues with converting an old big integer class may be due int vs. bool in an if(). No longer have access to the old compiler, so can not test the old behavior.


[Edit]
Using the answers below and some more research:
Answer: Yes, many pre ISO Standard C++ versions (mid 1980s -1998), that lacked a bool, did use casts to int (or other numeric types). Significant compiler variation existed - it was pre-standard.

The first C++ ISO standard came out in 1998 (ISO/IEC 14882:1998 aka C++98). It defined the bool type. Thus ISO standard C++ has always used the bool cast in if().

4

2 回答 2

6

我不能肯定地直接回答这个问题,但是Herb Sutter 说bool1990 年发布的 C++ 的预标准版本中没有类型。

因此,if不可能使用过operator bool(),而且在我看来,operator int()如果它确实有效,它很可能会使用。不过,我没有 1990 年 C++ 参考手册的副本可以确认。

于 2013-06-07T23:25:45.833 回答
4

不在标准 C++ 中。严格来说,在标准 C++ 中, if 语句尝试将其中包含的表达式转换为bool,然后根据该表达式改变行为。

ISO/IEC 14882:2003 4.12 [conv.bool]/1:

算术、枚举、指针或指向成员类型的指针的右值可以转换为 bool 类型的右值。将零值、空指针值或空成员指针值转换为 false;任何其他值都将转换为 true。

6.4.1 [stmt.if]/1:

如果条件 (6.4) 为真,则执行第一个子语句。如果选择语句的 else 部分存在并且条件为 false,则执行第二个子语句。在 if 语句的第二种形式(包括 else 的那个)中,如果第一个子语句也是 if 语句,则内部 if 语句应包含 else 部分。76)

请注意对“真”和“假”的明确引用,它们是布尔概念。

于 2013-06-07T23:20:17.323 回答