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

时间:2022-08-10 19:39:02

I know it is a common issue, but looking for references and other material I don't find a clear answer to this question.

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

Consider the following code:

考虑下面的代码:

#include <string>

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

The compiler tells me it cannot find an overloaded operator for char[dim].

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

Does it mean that in the string there is not a + operator?

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

But in several examples there is a situation like this one. If this is not the correct way to concat more strings, what is the best way?

但是在一些例子中有这样的情况。如果这不是处理更多字符串的正确方法,那么最好的方法是什么?

4 个解决方案

#1


150  

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:

这是行不通的,因为对于c++来说,这似乎是在添加两个char指针。相反,您需要将至少一个char*常量转换为std::string。你可以做你在问题中已经发布的东西(如我所说,这个代码将会工作),或者你做以下事情:

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

#2


46  

std::string a = "Hello ";
a += "World";

#3


5  

I would do this:

我想这样做:

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

Which compiles in VS2008.

在VS2008中编译。

#4


5  

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

#1


150  

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:

这是行不通的,因为对于c++来说,这似乎是在添加两个char指针。相反,您需要将至少一个char*常量转换为std::string。你可以做你在问题中已经发布的东西(如我所说,这个代码将会工作),或者你做以下事情:

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

#2


46  

std::string a = "Hello ";
a += "World";

#3


5  

I would do this:

我想这样做:

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

Which compiles in VS2008.

在VS2008中编译。

#4


5  

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