【问题标题】:C++ cout not accepting strings or strings with + [duplicate]C ++ cout不接受字符串或带有+的字符串[重复]
【发布时间】:2019-11-26 22:51:59
【问题描述】:
class Book {
public:
    string title;
    string author;

    void readBook() {

        cout << "Reading" + this->title + " by " + this->author << endl;
    }
};

这会导致以下错误。

binary '<<': no operator found which takes a right-hand operand of type 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' 

其次

cout << part1 << endl;

这是导致此错误的原因。

Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'std::string'   

我的包含语句

#include <string>
#include "pch.h"
#include <iostream>
#include <vector>
#include <exception>
#include <stdio.h>
#include <Windows.h>
using namespace std;

全部在 VS 2017 中。

我可以得到要打印的字符串

cout << part1.c_str() << part2.c_str() << endl;

有人可以向我解释为什么它不会在没有.c_str() 的情况下打印字符串以及为什么它不接受多个字符串?我正在学习教程,导师能够正确处理这些变量。

【问题讨论】:

  • 无法使用minimal reproducible example 进行复制。见ideone.com/yKq4yi
  • 如果op&lt;&lt; 不在范围内,那么那里的事情就会变得非常不稳定。提交minimal reproducible example
  • #include &lt;string&gt; 应该在#include "pch.h" 之后
  • Visual Studio 完全忽略在#include 预编译头文件之前键入的任何内容。
  • pch.h 中有什么 - 我们假设它是一个预编译的头文件,但它是吗?

标签: c++ visual-studio cout


【解决方案1】:

cout &lt;&lt; somethig是通过运算符重载实现的..

operator &lt;&lt;( const char * ) 存在..

但是operator &lt;&lt;( string ) 不存在..

c_str() 返回const char *。所以,你可以用cout &lt;&lt;

这会起作用..

cout &lt;&lt; "Reading" &lt;&lt; this-&gt;title.c_str() &lt;&lt; " by " &lt;&lt; this-&gt;author.c_str() &lt;&lt; endl;

【讨论】:

  • OP 已经指出他们知道他们可以使用c_str() 来让它工作。 operator&lt;&lt;(std::string) 确实存在:它存在OP包含的&lt;string&gt;标头
  • @Tas 请看一下错误信息..它说它不存在..
猜你喜欢
  • 2016-10-28
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
相关资源
最近更新 更多