c++ - 评估语句 cin==(expression)

标签 c++ return-value cout cin

下面的代码打算做什么?

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() returns true, otherwise returns a non-null pointer. This pointer is implicitly convertible to bool 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*() constexplicit operator bool() const 取代. explicit是关键,因为它意味着转换函数只能显式使用(如通过直接强制转换)或在 bool 上下文中使用,如:

if (cin) { // calls cin.operator bool()
}

相等不是 bool 上下文,所以在表达式中

cin == cout

那个转换函数不会被调用。因为没有 operator==定义于 std::basic_ios (或 std::istreamstd::ostream ),表达式将无法编译。

关于c++ - 评估语句 cin==(expression),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31656036/

相关文章:

c++ - GetAsyncKeyState 不工作

c# - 如何在 C# 中编码数据类型 unsigned char**?

c++ - boolean : Incorrect output of cout not 0 or 1

c++ - 如何使用 Qt 创建项目符号列表或编号列表?

c++ - OpenCV : undefined reference to imread()

sql-server-2008 - 如何将值从动态 SQL 存储过程返回到 Entity Framework ?

casting - 在 Go 中对多个返回值进行转换/类型断言的惯用方法

php/mysql 数组或带有某些值的查询

使用 cout << 打印字符串时 CodeBlocks 中的 C++ 运行时错误

c++ - wcout 是如何工作的?