我正在阅读 Scott Meyers 的 Effective C++ 一书,并在阅读第 3 项 - 尽可能使用 const
时发现这个示例非常具有误导性。
我的问题是 - 数组访问如何返回感兴趣索引处的引用而不是该索引处的项目。
同时附上我执行的程序以供引用
#include <iostream>
#include <string>
using namespace std;
class TextBlock
{
public:
explicit TextBlock(const std::string str) : text(str) {}
const char& operator[](std::size_t position) const { return text[position]; }
char& operator[](std::size_t position) { return text[position]; }
std::string get_text() { return text; }
private:
std::string text;
};
int main()
{
TextBlock tb("Hello");
cout << "Before calling operator overloading " << tb.get_text() << "\n";
tb[0] = 'I';
cout << "After calling operator overloading " << tb.get_text() << "\n";
return 0;
}
我得到了相应的输出
Before calling operator overloading Hello
After calling operator overloading Iello
观察到的行为是否特定于运算符重载?
最佳答案
My question is - How can an array access return a reference at the interested index rather than the item at that index.
它不是数组访问。当您执行 text[position]
时,您正在调用 std::string
的以下重载。
char& std::string::operator [] ( std::size_t index ) ;
它返回对字符串指定位置中字符的引用,它实际上是字符的容器。这类似于其他容器的工作方式,例如 std::map
或 std::vector
。通过重载类的索引运算符可以实现此行为。否则它将是未定义的,因为索引只能在指针/数组或实现了重载的类上实现。
话虽如此,应该记住数组索引实际上是指针解引用,这意味着它可以以相同的方式绑定(bind)到引用并导致相同的结果,如下所示(试试看)。这是因为 carray[i]
等同于 *(carray + i)
这是一种告诉编译器可以将指针隐式转换为引用的方法。
char& operator [] ( std::size_t i ) { return carray[i]; }
...
char carray[10];
索引运算符的实现有很好的理由。它有效地允许您像对待 char[]
一样对待 std::string
;您可以为任何给定索引分配一个值,也可以访问任何给定索引以获取值。
关于c++ - std::string operator[] 如何返回引用而不是字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29186152/