http://c.biancheng.net/view/1446.html
1.下标操作符[] 和 成员函数at()
需要注意的是,这两种访问方法是有区别的:
- 下标操作符 [] 在使用时不检查索引的有效性,如果下标超出字符的长度范围,会示导致未定义行为。对于常量字符串,使用下标操作符时,字符串的最后字符(即 ' ')是有效的。对应 string 类型对象(常量型)最后一个字符的下标是有效的,调用返回字符 ' '。
- 函数 at() 在使用时会检查下标是否有效。如果给定的下标超出字符的长度范围,系统会抛出 out_of_range 异常。
总的来说,at()函数更加安全,会检查是否有效,所以多使用at()函数来代替[]。
#include <iostream> #include <string> int main() { const std::string cS ("c.biancheng.net"); std::string s ("abode"); char temp =0; char temp_1 = 0; char temp_2 = 0; char temp_3 = 0; char temp_4 = 0; char temp_5 = 0; temp = s [2]; //"获取字符 'c' temp_1 = s.at(2); //获取字符 'c' temp_2 = s [s.length()]; //未定义行为,返回字符' ',但Visual C++ 2012执行时未报错 temp_3 = cS[cS.length()]; //指向字符 ' ' temp_4 = s.at (s.length ()); //程序异常 temp_5 = cS.at(cS.length ()); //程序异常 std::cout << temp <<temp_1 << temp_2 << temp_3 << temp_4 << temp_5 << std::endl; return 0; }