C++ cout 不接受带有 + 的字符串或字符串

标签 c++ visual-studio cout

<分区>

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() 的字符串以及为什么它不接受多个字符串吗?我正在学习教程,导师能够毫无错误地处理这些变量。

最佳答案

cout << somethig通过运算符重载实现..

operator <<( const char * )是存在的..

但是operator <<( string )不存在..

c_str()返回 const char * .所以,您可以将它与 cout << 一起使用

这会起作用..

cout << "Reading" << this->title.c_str() << " by " << this->author.c_str() << endl;

关于C++ cout 不接受带有 + 的字符串或字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59060560/

相关文章:

c# - OpenSSL 错误 "data greater than mod len"

c# - 如何同时为 x86 和 x64 配置 VS2012 解决方案

C++:如何创建一个接受连接字符串作为参数的函数?

c++ - 使用 "cout"在 Windows 对话框中显示消息 - C++

c++ - 从 Visual Studio 运行应用程序会导致错误(由 CMake 生成)

c++ - Xcode 使用 C++ 在控制台中不显示任何内容

c++ - 如何从字符串中复制每 16 个字节的数据?

c++ - 在 C++ 对象上使用 extern 时 undefined reference ,但不是整数类型

c++ - 为什么 iostream::eof 在循环条件(即 `while (!stream.eof())` )内被认为是错误的?

c++ - 错误 : LNK1104: cannot open file