14.5. Subscript Operator14.5. 下标操作符Classes that represent containers from which individual elements can be retrieved usually define the subscript operator, operator[]. The library classes, string and vector, are examples of classes that define the subscript operator. 可以从容器中检索单个元素的容器类一般会定义下标操作符,即 operator[]。标准库的类 string 和 vector 均是定义了下标操作符的类的例子。
Providing Read and Write Access提供读写访问One complication in defining the subscript operator is that we want it to do the right thing when used as either the left- or right-hand operand of an assignment. To appear on the left-hand side, it must yield an lvalue, which we can achieve by specifying the return type as a reference. As long as subscript returns a reference, it can be used on either side of an assignment. 定义下标操作符比较复杂的地方在于,它在用作赋值的左右操作符数时都应该能表现正常。下标操作符出现在左边,必须生成左值,可以指定引用作为返回类型而得到左值。只要下标操作符返回引用,就可用作赋值的任意一方。 It is also a good idea to be able to subscript const and nonconst objects. When applied to a const object, the return should be a const reference so that it is not usable as the target of an assignment. 可以对 const 和非 const 对象使用下标也是个好主意。应用于 const 对象时,返回值应为 const 引用,因此不能用作赋值的目标。
Prototypical Subscript Operator原型下标操作符The following class defines the subscript operator. For simplicity, we assume the data Foo holds are stored in a vector<int>: 下面的类定义了下标操作符。为简单起见,假定 Foo 所保存的数据存储在一个 vector<int>: 中: class Foo { public: int &operator[] (const size_t); const int &operator[] (const size_t) const; // other interface members private: vector<int> data; // other member data and private utility functions }; The subscript operators themselves would look something like: 下标操作符本身可能看起来像这样: int& Foo::operator[] (const size_t index) { return data[index]; // no range checking on index } const int& Foo::operator[] (const size_t index) const { return data[index]; // no range checking on index }
![]() |