加号运算符不接受原始字符串操作数

时间:2015-02-02 23:47:58

标签: c++

尝试打印连接字符串时出错:

std::cout << "some string" + "another string";

我收到此错误:

Operator does not take these operands.

我认为"some string"是一个std::string字面值。发生了什么事?

3 个答案:

答案 0 :(得分:3)

二进制+不应该使用这些操作数。 C ++语言没有这样的+运算符,也没有运算符。您不能相互添加两个字符串文字。

为什么你在问题标题中提到std::string对我来说并不清楚。您的示例中没有std::string。字符串文字不是std::string个对象。字符串文字只是const char的数组。它们与std::string无关,并且它们不会为您神奇地转换为std::string

如果您想在这种情况下使用std::string,则必须将至少一个文字明确转换为std:string

cout << std::string("some string") + "another string";

如果重载决策规则将使编译器考虑+对象的二进制std::string运算符,并隐式地将第二个操作数转换为std::string

答案 1 :(得分:3)

那些不是std::string - 操作数,其中+真正连接,但字符串文字

字符串文字表示常量字符数组(包括隐式0终止符),这些字符不可添加(const char[])。它们都没有腐烂的指针。

尽管如此,将它们连接起来非常简单:只留下它们之间的任何内容,只留下空白,编译器会为你完成它。

另外,since C++14 one can actually write std::string-literals

#include <string>
using namespace std::literals::string_literals;
// the last two are inline-namespace, could leave them off to get more.

...

"std::string-literal"s // Note the `s` behind the string-literal.

答案 2 :(得分:1)

要创建std::string文字,您必须执行以下操作:

#include <string>
#include <iostream>
int main() {
  using namespace std::string_literals;
  std::cout << "some string"s + "another string"s; 
}

注意尾随s

序列"some string"不是std::string字面值,而是原始字符的const char[12]缓冲区。这来自C,其中没有std::string。此外,这意味着如果您更喜欢不同的字符串库,std::string没有内置优势。

随着您使用s进行后期修复(将文字带入视图后),您将获得std::string字面值。

这是一个C ++ 14功能。在C ++ 03中,你可以通过

获得类似的效果
#include <string>
#include <iostream>
int main() {
  std::cout << std::string("some string") + std::string("another string");
}