串联字符串不能像预期的那样工作

我知道这是一个常见的问题,但是在寻找参考资料和其他材料时,我没有找到这个问题的明确答案。

考虑以下代码:

#include <string>


// ...
// in a method
std::string a = "Hello ";
std::string b = "World";
std::string c = a + b;

编译器告诉我它找不到 char[dim]的重载运算符。

这是否意味着字符串中没有 + 运算符?

但是在几个例子中有一个类似的情况。如果这不是连接更多字符串的正确方法,那么最好的方法是什么?

221490 次浏览
std::string a = "Hello ";
a += "World";

I would do this:

std::string a("Hello ");
std::string b("World");
std::string c = a + b;

Which compiles in VS2008.

std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:

std::string c = "hello" + "world";

This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:

std::string c = std::string("hello") + "world";