Team LiB
Previous Section Next Section

14.5. Subscript Operator

14.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[]。标准库的类 stringvector 均是定义了下标操作符的类的例子。

The subscript operator must be defined as a class member function.

下标操作符必须定义为类成员函数。



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 引用,因此不能用作赋值的目标。

Ordinarily, a class that defines subscript needs to define two versions: one that is a nonconst member and returns a reference and one that is a const member and returns a const reference.

类定义下标操作符时,一般需要定义两个版本:一个为非 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
     }

Exercises Section 14.5

Exercise 14.17:

Define a subscript operator that returns a name from the waiting list for the CheckoutRecord class from the exercises to Section 14.2.1 (p. 515).

第 14.2.1 节习题中定义了一个 CheckoutRecord 类,为该类定义一个下标操作符,从等待列表中返回一个名字。

Exercise 14.18:

Discuss the pros and cons of implementing this operation using the subscript operator.

讨论用下标操作符实现这个操作的优缺点。

Exercise 14.19:

Suggest alternative ways to define this operation.

提出另一种方法定义这个操作。


Team LiB
Previous Section Next Section