`cout&lt;&lt; <x`和`cout.operator&lt;&lt;(x)`? [英] Difference between `cout &lt;&lt; x` and `cout.operator &lt;&lt;(x)`?

查看:55
本文介绍了`cout&lt;&lt; <x`和`cout.operator&lt;&lt;(x)`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用for_each将字符串向量打印到cout.但是,在编写该语句时,我发现未定义 std :: ostream :: operator<<(const std :: string&); 会导致编译器错误.以下代码说明了该问题:

I've been trying to use for_each to print a vector of strings to cout. However, when formulating the statement I found that std::ostream::operator<<(const std::string &); is not defined leading to compiler errors. The following code illustrates the problem:

#include <iostream>
#include <string>


int main()
{
    std::string message = "Hello World!\n";

    // This works
    std::cout << message;

    // Compiler error
    std::cout.operator <<(message);
}

我认为这两个语句应该看起来与编译器相同.显然他们不是.那有什么区别呢?

I thought that both statements should appear identical to the compiler. Apparently they are not. So what is the difference then?

正如Tomalak和Prasoon所说,我需要调用此函数:

As Tomalak and Prasoon indicated I needed to call this function:

std::ostream& operator<<(std::ostream&, const std::string&);

因此,以下示例将起作用:

So the following sample will work:

#include <iostream>
#include <string>


int main()
{
    std::string message = "Hello World!\n";
    operator<<(std::cout, message);
}

关于我的最初目标(使用for_each打印字符串向量):似乎最好将 std :: copy std :: ostream_iterator 一起使用图示如下:如何使用for_each输出到cout?

Concerning my original goal (to use for_each to print a vector of strings): It seems like it's better to use std::copy with std::ostream_iterator as illustrated here: How do I use for_each to output to cout?

推荐答案

您正在寻找 std :: ostream&运算符<((std :: ostream& ;, const std :: string&); .这是一个免费功能.

You're looking for std::ostream& operator<<(std::ostream&, const std::string&);. It's a free function.

这篇关于`cout&lt;&lt; <x`和`cout.operator&lt;&lt;(x)`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆