代码如下图所示,在main函数中,有两个string类型的变量,其中一个变量str1我直接初始化,另一个变量str2我没有初始化,但是string类型调用默认构造函数,使得str2 = "\0",是这样吧。我对str1的首字符进行了变换,然后用cout可以在后面输出,为什么我对str2的首字符进行变换后,再用cout输出,但是没有得到正确的输出啊。请问这是怎么回事啊?谢谢。
#include <iostream>
#include <string>
int main()
{
std::string str1 = "test";
std::string str2;
if (str2[0] == '\0')
std::cout << "yes" << std::endl;
str1[0] = 'a';
str2[0] = 'b';
std::cout << str1 << '\n'
<< str2 << '\n';
str2[1] ='\0';
std::cout << str1 << '\n'
<< str2 << '\n';
return 0;
}
运行结果:
PHP中文网2017-04-17 13:30:14
#include <iostream>
#include <string>
int main()
{
std::string str1 = "test"; //有效长度4(不包含'rrreee')
std::string str2; //有效长度0
//前面声明其实和 str1[4], str2[0]没什么不同
// c++ string类并没有智能到 像其他的一些语言
// 你访问没有分配的字符下标 自动分配内存的地步
// 正如str2[0] 你并没有分配任何内存,也就不能访问了
if (str2[0] == 'rrreee') //这个访问是 错误的,如果你判断是否为空请用 .empty
std::cout << "yes" << std::endl;
str1[0] = 'a'; //如果你非要这么做可以使用 .insert的重载
str2[0] = 'b';
std::cout << str1 << '\n'
<< str2 << '\n';
str2[1] ='rrreee';
std::cout << str1 << '\n'
<< str2 << '\n';
return 0;
}
伊谢尔伦2017-04-17 13:30:14
According to your question.
You created str1, which points to five bytes.
And str2 is empty.
So
you use str1[0]str1[1 ]str1[2]str1[3]str1[4] is fine
But there will be a problem if you use str2[0]. It actually does not point to any memory.
Personal suggestion.
You use C++, it is not recommended to use array subscripts in C language to access.
It would be better to use some functions that come with string to access.
阿神2017-04-17 13:30:14
When you output, try outputting str2.data() instead.
str2[0] = 'b'; Should this operation be effective? This question is worth thinking about
because currently str2 is an empty string, that is, empty()==true;
then its size() should be 0, and str2[0] is for the first element access.
This is actually related to the implementation of std::string. You can try it. Some compilers’ built-in implementations will cause errors during this operation.
/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h:707: typename _Alloc::rebind<_CharT>::other::reference std::basic_string<_CharT, _Traits, _Alloc>::operator[](typename _Alloc::rebind<_CharT>::other::size_type) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]: Assertion '__pos < size()' failed.
Disallowed system call: SYS_kill