实际问题是在C++中使用“+”连接字符串文字会出错:
```
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
```
上面的代码会产生错误。
在C++(以及C)中,您只需将字符串文字放在彼此旁边即可将它们串联起来。
string s0 = "Hello world, " "nice to see you, " "or not.";
string s1 = "Hello world, " /*same*/ "nice to see you, " /*result*/ "or not.";
string s2 =
"Hello world, " /*line breaks in source code as well as*/
"nice to see you, " /*comments don't matter*/
"or not.";
如果你在宏中生成代码,这是有意义的:
#define TRACE(arg) cout << #arg ":" << (arg) << endl;
…一个可以像这样使用的简单宏
int a = 5;
TRACE(a)
a += 7;
TRACE(a)
TRACE(a+7)
TRACE(17*11)
(演示...)
或者,如果您坚持使用+
来连接字符串字面量(如underscore_d所建议的):
string s = string("Hello world, ")+"nice to see you, "+"or not.";
另一种解决方案是在每个连接步骤中结合一个字符串和一个const char*
string s;
s += "Hello world, "
s += "nice to see you, "
s += "or not.";
char *
指针相加。这就是导致错误的原因 - 因为对指针求和是没有意义的。如下所述,将至少第一个操作数转换为std::string
,就不会出现错误了。 - underscore_d