std::string 的运算符 [] 和常量运算符 [] 之间的区别
Difference between std::string's operator[] and const operator[]
有人能解释一下之间的区别吗
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 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(,因此承诺不更改任何成员。确保你可以;t通过返回的引用更改内部成员这也是常量。
const char& operator[](int i) const
// ^^^^^ this means the method will not change the state
// of the string.
//^^^^^^^^^^^ This means the object returned refers to an internal member of
// the object. To make sure you can't change the state of the string
// it is a constant reference.
这允许您从字符串中读取成员:
std::string const st("Plop is here");
char x = st[2]; // Valid to read gets 'o'
st[1] = 'o'; // Will fail to compile.
对于第二个版本,它说我们返回对内部成员的引用。两者都不承诺该对象不会被更改。因此,您可以通过引用更改字符串。
char& operator[](int i)
// ^^^^^ Returns a reference to an internal member.
std::string mu("Hi there Pan");
char y = mu[1]; // Valid to read gets 'i'
mu[9] ='M'; // Valid to modify the object.
std::cout << mu << "n"; // Prints Hi there Man
第二个是真的在复制字符串吗?为什么?
没有。因为事实并非如此。
问题在于常量正确性。允许在常量字符串中进行只读访问和允许在可变字符串中进行可写访问需要两种方法。
如果要从const std::string
访问字符,则const char& operator[] const
访问器是必需的。char& operator[]
访问器是修改std::string
中的字符所必需的。
第二个不需要复制字符串。它只是返回一个对可修改字符的引用。第一个返回一个不可修改的引用,因为它必须:函数本身是const,这意味着它不能改变字符串的状态。
现在,如果您有写时复制字符串(有时会使用优化(,那么获得对字符串片段的非常量引用可能意味着复制(因为引用意味着写入(。这可能发生在您的特定平台上,也可能不会发生(您没有具体说明(。
一些基础知识:
使用运算符[],您既可以编辑容器/内存中的值,也可以读取值。使用
const char& operator[] const
时,您只能读取值。例如。
std::string ss("text");
char a = ss[1];
使用char& operator[]
可以编辑该值。例如
ss[1] = 'A';
- 构造函数和转换运算符之间的重载解析
- 编译器如何在前缀和 postix 运算符之间进行区分?
- 你能帮我了解重载一元运算符和二进制运算符之间的区别吗?
- 赋值运算符之间的差(+=和=)
- C++ 字符串追加和运算符 += 之间的区别
- 为什么赋值运算符和相等运算符之间没有 1:1 的关系?
- "&&"运算符和"and"运算符之间的区别
- 显式运算符 = 调用和 = 运算符之间是否有区别
- 内部和外部过载C++运算符之间的差异
- 在运算符之间添加间距的目的是什么?
- 如何确保此 qi 解析器不允许点运算符之间的空格
- 点运算符和箭头运算符之间的区别 结构对象变量 在 C 或 C++ 中创建树
- :、::运算符之间的C++差异
- 函数调用中 * 和 & 运算符之间的区别
- C++中转换运算符之间的优先级
- QSharedPointer::isNull() 和运算符之间的区别!().
- istream的运算符之间的差异>>libc++和libstdc++之间的double&val)
- 复制构造函数和赋值运算符之间的区别
- C++ 中 += 和 =+ 运算符之间的差异
- 显式原子加载/存储与常用运算符=和运算符T之间的区别是什么