Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么空字符串可以在C++; #包括 #包括 使用std::string; 使用std::cout; 使用std::endl; int main() { 字符串s; cout_C++ - Fatal编程技术网

C++ 为什么空字符串可以在C++; #包括 #包括 使用std::string; 使用std::cout; 使用std::endl; int main() { 字符串s; cout

C++ 为什么空字符串可以在C++; #包括 #包括 使用std::string; 使用std::cout; 使用std::endl; int main() { 字符串s; cout,c++,C++,有一个特殊的规则,您可以访问s[n],其中n是s的长度。结果是一个空字符(即初始化字符类型的值)并且试图修改它会导致未定义的行为。是产生s[n]的基本原理对于一个类似于C风格字符串的字符串行为,实现为char[n+1]?@Barmar我想是这样的。详细的原理可能在某个地方可以找到,但我太懒了,没有去挖掘它。@Deduplicator,是的,它是§21.4.5[string.access]@quantdev:Seen。s[s.size()]但是,不能修改,这是关于它的唯一特殊规则。无论std::s

有一个特殊的规则,您可以访问
s[n]
,其中
n
s
的长度。结果是一个空字符(即初始化字符类型的值)并且试图修改它会导致未定义的行为。

是产生
s[n]的基本原理
对于一个类似于C风格字符串的字符串行为,实现为
char[n+1]
?@Barmar我想是这样的。详细的原理可能在某个地方可以找到,但我太懒了,没有去挖掘它。@Deduplicator,是的,它是§21.4.5[string.access]@quantdev:Seen。
s[s.size()]但是,
不能修改,这是关于它的唯一特殊规则。无论
std::string
的缓冲区是否以null结尾,它不是实现定义的吗?
#include<iostream>
#include<string>

using std::string;
using std::cout;
using std::endl;

int main()
{
    string s;
    cout << s.size() << endl;
    cout << s[0] << endl;  //output empty line
    return 0;
}