为什么通过添加字符串文字和char初始化时,为什么不打印字符串

Why is string not getting printed when being initialized by adding string literal and a char

本文关键字:字符串 初始化 打印 为什么不 char 添加 文字 为什么      更新时间:2023-10-16

在情况1中,输出为空白当我初始化这样的字符串时:

 #include <iostream>
 #include<string>
 using namespace std;
 //CODE 1
 int main()
 {
    string s="hello" + 'c';
    cout<<s<<endl;
    return 0;
 }

但是当我以这种方式写作时,它可以正常工作:

 #include <iostream>
 #include<string>
 using namespace std;
 //CODE 2
 int main()
 {
     string s="hello";
     char k='c';
     s+=k;
     cout<<s<<endl;
     return 0;
 }

现在,我很困惑,就像在堆栈溢出上问的另一个问题中,它说 namepace std 使用了字符串和std :: string之间没有区别> -> String和STD :: String之间没有功能差异,因为它们是相同的类型std :: string vs string在C 中而为此问题提供的答案指向差异:

编译器是G (GCC)4.8.5 20150623(红帽4.8.5-4)

string s="hello" + 'c';

等于

string s=("hello" + 'c');

ASCII编码与

相同
string s=("hello" + 99);

相同
string s=(&"hello"[99]);

也就是说,您得到了字符串"hello"的100个元素的指针,该元素只有六个元素(不要忘记终结者)。

超出范围导致不确定的行为

,因为 "string"不是 std::string,而是 const char*,而指针加上一个数字(字符为"仅"数字)使用指针算术,因此添加后,您将获得const char*,可能指向字符串字面之后的垃圾记忆。

第二个示例有效,因为在这种情况下,s std::string,它具有CHAN的operator +=,并且> not 使用Pointer Arithmetic。

代码不同。在

string s="hello" + 'c';

"hello"不是std::string。它是字符串文字,具有const char[N]的类型。当您将字符添加到数组衰减到指针时,您正在执行指针算术。该算术正在超过字符串字面的末端,因此它是未定义的行为。

为了获得第一个代码,就像第二个示例一样,您需要将"hello"作为字符串。您可以将用户定义的文字用于std::string,例如

string s = "hello"s + 'c';

或仅使用构造函数

string s = std::string("hello") + 'c';

表达式 "hello" + 'c';正在将char类型添加到const char[6]类型中,并具有晦涩的结果。正式地,第一个参数腐烂到const char*指针,并且使用指针算术算术的正常规则添加了c。该行为可能是可能的未定义,因为我曾经遇到过的c的数字值是所有编码,一个大于6的值,因此您最终试图尝试索引 const char阵列"hello"

之外的元素

在第二版中,您将std::string类的过载+=运算符以char为参数,并且字符c conpateNated 到该字符串。

"hello" + 'c'给出了"hello"末端的指针(例如,假设ASCII字符集,'c'具有数字值99,并且"hello" + 99给出了一个指向以前的99字符的指针'h'"hello"中)。

使用这样的指针来初始化std::string提供了不确定的行为。

"代码2"工作std::string具有接受charoperator+=(),并将其附加到字符串的末端。