程序一:
#include <iostream>
using namespace std;
int main() {
string str;
char temp = 'a';
str += temp + "bc";
cout << str;
return 0;
}
输出:
未知字符
程序2:
#include <iostream>
using namespace std;
int main() {
string str;
char temp = 'a';
str += temp;
str += "bc";
cout << str;
return 0;
}
输出:
abc
为什么两个输出不同?两个输出不应该相同吗?
最佳答案
这个说法
str += temp + "bc";
可以表示为
str = str + ( temp + "bc" )
;在子表达式
temp + "bc"
中字符串文字 "bc"
隐式转换为指向其第一个字符的指针,类型为 const char *
.变量值temp
由于整数提升,例如在 ASCII 表中具有值 97
.所以在子表达式中使用了指针算法。表达式
temp + "bc"
指向字符串文字之外的内存。所以表达式的结果是未定义的。如果你会写例如
char temp = 1;
然后表达式 temp +
"bc"
指向字符串文字的第二个字符。结果str
将具有值 'b'
.或者要获得与您可以编写的第二个程序相同的结果
str += temp + std::string( "bc" );
至于第二个程序然后在这个语句中
str += temp;
str += "bc";
使用了重载运算符
+=
对于 std::string 类和 char
类型的对象和 char *
.所以这些陈述是明确定义的。请注意,您应该明确包含标题
<string>
.#include <string>
关于c++ - 添加这些字符串有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60043601/