c++ - 为什么在通过添加字符串文字和 char 进行初始化时不打印字符串

标签 c++ string

<分区>

在情况 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;
 }

现在我很困惑,因为在另一个关于堆栈溢出的问题中,它说当使用 namespace std 时,string 和 std::string 之间没有区别,这些答案是说 -> string 和 std::string 之间没有功能差异,因为它们是同一类型 std::string vs string in c++ 而为这个问题提供的答案却指出了不同点:

编译器是 g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)

最佳答案

当你有

string s="hello" + 'c';

等于

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

ASCII encoding

一样
string s=("hello" + 99);

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

也就是说,您得到一个指向字符串 "hello" 的第 100 个元素的指针,它只有六个元素(不要忘记终止符)。

越界会导致未定义的行为

关于c++ - 为什么在通过添加字符串文字和 char 进行初始化时不打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42764635/

相关文章:

c++ - OpenGL Nvidia 驱动程序 259.12 纹理不工作

c++ - 在 Visual Studio 2013 中将 libcurl 库静态链接到我的项目(一个 dll)

python - 在 python 中用子列表拆分字符串

c# - String.Split() 返回空值

java - 如果Java没有运算符重载, "string1"+ "string2"怎么可能?

c++ - 如何以正确的方式从容器中删除 QSharedPointer

c++ - 我怎样才能在同一行得到我程序的所有总和?

c++ - 升级到 win 10,然后我的 Direct3D11 项目无法链接

javascript - jquery:将[object Object]附加到字符串

java - 如何使用正则表达式获取文件扩展名?