连接字符串无法按预期工作
我知道这是一个常见问题,但在寻找参考资料和其他材料时,我没有找到这个问题的明确答案。
考虑以下代码:
#include <string>
// ...
// in a method
std::string a = "Hello ";
std::string b = "World";
std::string c = a + b;
编译器告诉我它找不到 char[dim]
的重载运算符。
这是否意味着字符串中没有 + 运算符?
但在几个例子中都存在这样的情况。如果这不是连接更多字符串的正确方法,那么最好的方法是什么?
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]
.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您编写的代码可以正常工作。您可能正在尝试实现一些不相关但相似的东西:
这不起作用,因为对于 C++ 来说,这似乎是您正在尝试添加两个
char
指针。相反,您需要将至少一个char*
文字转换为std::string
。您可以执行问题中已发布的操作(正如我所说,此代码将工作),或者执行以下操作:Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:
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 thechar*
literals to astd::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:我会这样做:
在 VS2008 中编译。
I would do this:
Which compiles in VS2008.