连接字符串无法按预期工作

发布于 2024-10-05 04:19:33 字数 344 浏览 0 评论 0原文

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

考虑以下代码:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

牵你的手,一向走下去 2024-10-12 04:19:33

您编写的代码可以正常工作。您可能正在尝试实现一些不相关但相似的东西:

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

这不起作用,因为对于 C++ 来说,这似乎是您正在尝试添加两个 char 指针。相反,您需要将至少一个char* 文字转换为std::string。您可以执行问题中已发布的操作(正如我所说,此代码工作),或者执行以下操作:

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

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";
檐上三寸雪 2024-10-12 04:19:33
std::string a = "Hello ";
a += "World";
std::string a = "Hello ";
a += "World";
櫻之舞 2024-10-12 04:19:33

我会这样做:

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

在 VS2008 中编译。

I would do this:

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

Which compiles in VS2008.

终陌 2024-10-12 04:19:33
std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);
std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文