【发布时间】:2015-03-21 18:04:56
【问题描述】:
我正在阅读 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
观察到的行为是否特定于运算符重载?
【问题讨论】:
-
std::string的重载运算符[]返回一个引用,您只是从班级的重载[]转发它。所以你得到一个作为操作符结果的引用,并且可以使用这个引用来修改字符串内容。你的意图是什么? -
@AlexShesterov 我想知道如何通过索引值访问字符串会返回对感兴趣位置的引用,而不是有问题的项目。你的回答帮助了我。这是一个需要投反对票的基本疑问吗?
-
我没有否决您的问题。我会给你一个赞成票来补偿
-1。 -
why
operator[]通常返回引用的原因是数组索引表达式产生左值。也就是说,设int arr[10] = {};,那么表达式arr[2]是一个左值:arr[2] = 42;是良构的。std::string的重载的operator[]在这方面模仿了内置的数组索引