现代版本的 C++ 在评估 if()
语句中的条件时尝试使用类的 bool
运算符。其他转换运算符,例如 int
在不存在 bool
运算符时使用。如下所示。
#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;
}
运行这段代码不会产生任何意外:
TwoInts to bool
SixInts to int
查看一些旧的 C++ 代码,似乎有一个更改需要验证。
旧版本的 C++ 在评估 if()
语句中的条件时是否使用了类的 int
运算符?什么版本(如果有)做过某事?
那么建议的输出应该是
TwoInts to int
SixInts to int
关于问题原因的一些细节:转换旧的大整数类的问题可能是由于 int
与 bool
在 如果()
。无法再访问旧编译器,因此无法测试旧行为。
[编辑]
使用以下答案和更多研究:
回答:是的,许多缺少 bool
的 ISO 标准 C++ 之前的版本(1980 年代中期 -1998 年)确实使用了转换为 int
(或其他数字类型)。存在重要的编译器变体 - 它是准标准。
第一个 C++ ISO 标准于 1998 年发布(ISO/IEC 14882:1998 又名 C++98)。它定义了 bool
类型。因此,ISO 标准 C++ 始终使用 if()
中的 bool
转换。
最佳答案
我不能直接回答这个问题,但是Herb Sutter says 1990 年发布的 C++ 准标准版本中没有 bool
类型。
因此,if
不可能使用 operator bool()
,在我看来它很可能会使用 operator int()
如果它有效的话。不过,我没有 1990 C++ 引用手册的拷贝来确认。
关于c++ - 旧版本的 C++ 在评估 `int` 语句中的条件时是否使用了类的 `if()` 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16994263/