二进制表达式的操作数无效("常量字符*"和"常量字符*")

Invalid operands to binary expression ('const char*' and 'const char *')

本文关键字:常量 字符 表达式 操作数 无效 二进制      更新时间:2023-10-16

我想知道这个错误的原因,请用简单的单词。

#include <iostream>
#include <string>
int main()
{
    std::string exclam = "!";
    std::string message = "Hello" + ", world" + exclam;
    std::cout << message << std::endl;
    return 0;
}

test.cpp:55:35:错误:二进制表达式的操作数无效("常量字符*"和"常量字符*"( std::字符串消息 = "Hello" + ", world" + exclam;

"Hello"", world"不是字符串,它们是const char *,对于+运算符来说没有重载。

您必须执行以下操作:

std::string message = std::string("Hello") + std::string(", world") + exclam;