下面的代码打算做什么?
return cin==(cout<<(f(a)==f(b)?"YES":"NO"));
假设 f() 是一个返回字符串的函数并且 a 和 b 也是字符串并且函数的签名是
string f(string a)
提前致谢!
最佳答案
答案是:这取决于您编译所针对的 C++ 标准。归结为 std::basic_ios
中的转换函数
C++03
在这里,我们有 operator void*() const
,其中:
Returns a null pointer if
fail()
returnstrue
, otherwise returns a non-null pointer. This pointer is implicitly convertible tobool
and may be used in boolean contexts.
因此,在表达式中:
cin==(cout<<(f(a)==f(b)?"YES":"NO"));
我们将打印“YES”或“NO”,流输出的结果将是 cout
仍然(以 std::ostream&
的形式)。当我们进行相等性检查时,两个操作数都将隐式转换为 void*
。因此表达式检查两个流是否都失败了。这是一种特别模糊的做法:
cout << (f(a) == f(b) ? "YES" : "NO");
return cin.fail() && cout.fail();
C++11
对于 C++11,operator void*() const
被 explicit operator bool() const
取代. explicit
是关键,因为它意味着转换函数只能显式使用(如通过直接强制转换)或在 bool 上下文中使用,如:
if (cin) { // calls cin.operator bool()
}
相等不是 bool 上下文,所以在表达式中
cin == cout
那个转换函数不会被调用。因为没有 operator==
定义于 std::basic_ios
(或 std::istream
或 std::ostream
),表达式将无法编译。
关于c++ - 评估语句 cin==(expression),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31656036/