C++ 连接字符串不能按预期工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4304662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenating strings doesn't work as expected
提问by Andry
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?
但在几个例子中,有这样一种情况。如果这不是连接更多字符串的正确方法,那么最好的方法是什么?
回答by Konrad Rudolph
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 needto 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 willwork) or you do the following:
这不起作用,因为对于 C++,这似乎是您试图添加两个char
指针。相反,您需要将至少一个char*
文字转换为std::string
. 您可以执行您已经在问题中发布的内容(正如我所说,此代码将起作用),或者您执行以下操作:
std::string c = std::string("hello") + "world";
回答by Svisstack
std::string a = "Hello ";
a += "World";
回答by graham.reeds
I would do this:
我会这样做:
std::string a("Hello ");
std::string b("World");
std::string c = a + b;
Which compiles in VS2008.
在 VS2008 中编译。
回答by Teodor Pripoae
std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);