【问题标题】:How does the comma operator work with cout in C++?逗号运算符如何与 C++ 中的 cout 一起使用?
【发布时间】:2018-10-06 04:28:29
【问题描述】:

什么是返回值(未打印)

cout << 1, 2, 3, 4, 5;

如何调试这段代码?

我还需要解释一下 ostream 和 cout 是如何工作的。

【问题讨论】:

标签: c++ debugging


【解决方案1】:

返回值为int,其值为5。作为副作用,1 将被打印出来。

#include <iostream>

using namespace std;

int main(void)
{
    auto rv = (cout << 1, 2, 3, 4, 5);

    std::cout << rv;

    return 0;
}

【讨论】:

  • (cout &lt;&lt; 1), 2, 3, 4, 5
  • 视情况而定。如果你用括号括起来(cout &lt;&lt; 1, 2, 3, 4, 5),你会得到5。如果您不添加括号,而是分配给像auto r = cout &lt;&lt; 1, 2, 3, 4, 5 这样的变量,则= 运算符的绑定比, 更强,并且您将std::ostream&amp; 作为r 的类型。
  • @NiklasR 我首先尝试过,但它实际上无法为我编译,std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt;::operator =(const std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;)': attempting to reference a deleted function
  • @nvoigt 这是因为将变量声明为auto 不会推断出引用,因此r 的类型实际上将是std::ostream,即使分配的值是@987654337 @。 std::ostream 无法复制,因此出现“已删除函数”错误。将 r 声明为 auto&amp; 将使其成为 std::ostream&amp; 引用。
  • @RemyLebeau 你试过了吗?因为我将它明确设置为ostream&amp; 时遇到相同的错误,即使我拆分声明和分配时我仍然会得到它。
猜你喜欢
  • 2020-04-22
  • 2013-05-27
  • 1970-01-01
  • 2017-07-11
  • 2010-12-16
  • 2012-01-10
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多