And*_*dry 84 c++ string-concatenation standard-library stdstring operator-keyword
我知道这是一个常见的问题,但是在寻找参考资料和其他材料时,我找不到这个问题的明确答案.
请考虑以下代码:
#include <string>
// ...
// in a method
std::string a = "Hello ";
std::string b = "World";
std::string c = a + b;
Run Code Online (Sandbox Code Playgroud)
编译器告诉我它找不到重载的运算符char[dim]
.
这是否意味着在字符串中没有+运算符?
但在几个例子中,存在类似这样的情况.如果这不是连接更多字符串的正确方法,那么最好的方法是什么?
Kon*_*lph 152
您编写的代码可以正常工作.你可能想要实现一些不相关的东西,但是相似:
std::string c = "hello" + "world";
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为对于C++,这似乎是你想要添加两个char
指针.相反,您需要将至少一个char*
文字转换为std::string
.要么你可以做你已经在问题中发布的内容(正如我所说,这段代码可以使用),或者你执行以下操作:
std::string c = std::string("hello") + "world";
Run Code Online (Sandbox Code Playgroud)
Svi*_*ack 46
std::string a = "Hello ";
a += "World";
Run Code Online (Sandbox Code Playgroud)
我会这样做:
std::string a("Hello ");
std::string b("World");
std::string c = a + b;
Run Code Online (Sandbox Code Playgroud)
哪个在VS2008中编译.
std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
218046 次 |
最近记录: |