“const”的意思是“不能改变(*1)”。因此,您不能简单地将一个 const char 字符串“添加”到另一个 (*2)。您可以做的是将它们复制到非常量字符缓冲区中。
const char* a = ...;
const char* b = ...;
char buffer[256]; // <- danger, only storage for 256 characters.
strncpy(buffer, a, sizeof(buffer));
strncat(buffer, b, sizeof(buffer));
// now buffer has the two strings joined together.
由于类似原因,您尝试使用 std::string 失败。你说:
std::string a = "Start";
std::string b = a + " End";
这转化为
b = (std::string)a + (const char*)" End";
应该没问题,只是它创建了一个额外的字符串,你可能想要的是
std::string a = "Start";
a += " End";
如果您在执行此操作时遇到编译错误,请发布它们(确保您 #include )。
或者您可以执行以下操作:
std::string addTwoStrings(const std::string& a, const std::string& b)
{
return a + b; // works because they are both strings.
}
以下所有工作:(参见现场演示http://ideone.com/Ytohgs)
#include <iostream>
#include <string>
std::string addTwoStrings(const std::string& a, const std::string& b)
{
return a + b; // works because they are both strings.
}
void foo(const char* a, const char* b)
{
std::string str = a;
std::cout << "1st str = [" << str << "]" << std::endl;
str += " ";
std::cout << "2nd str = [" << str << "]" << std::endl;
str += b;
std::cout << "3rd str = [" << str << "]" << std::endl;
str = addTwoStrings(a, " ");
std::cout << "4th str = [" << str << "]" << std::endl;
str = addTwoStrings(str, b);
std::cout << "5th str = [" << str << "]" << std::endl;
}
int main()
{
foo("hello", "world");
}
*1 或更准确地说,“不能就地改变”——你可以在表达式等中使用它,例如,例如
const size_t len = strlen("hello");
size_t newLen = len + strlen("world");
// but this would not be legal:
len += 2; // error: len is const.
2 "const char a + const char* b" 实际上是尝试添加两个指针而不是两个字符串,结果将是字符串 a 的地址加上字符串 b 的地址,其总和将是某个随机内存位置