任何人都可以解释一下之间的区别:
const char& operator[] const
和
char& operator[]
在 C++ 中? 第二个是复制字符串是真的吗?为什么?
最佳答案
不,第二个返回对字符串中单个字符的非常量引用,因此您实际上可以使用它来更改字符串本身(字符串对象根本不重复,但其内容可能会被修改)。
std::string s = "Hell";
s[0] = 'B';
// s is "Bell" now
鉴于此示例,char& operator[]
当然可以用于访问单个字符而不修改它,例如 std::cout<< s[0];
.
然而,const
重载是必需的,因为您不能在 const 对象上调用非 const 成员函数。拿这个:
const std::string s = "Hell";
// ok, s is const, we cannot change it - but we still expect it to be accessible
std::cout << s[0];
// this, however, won't work, cannot modify a const char&
// s[0] = 'B';
通常,编译器会选择 const
仅在对 const 对象调用时才重载,否则它将始终倾向于使用非 const 方法。
关于c++ - std::string 的 operator[] 和 const operator[] 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7540699/