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 均是定义了下标操作符的类的例子。
| The subscript operator must be defined as a class member function. 下标操作符必须定义为类成员函数。 |
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 non const 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 non const member and returns a reference and one that is a const member and returns a const reference. 类定义下标操作符时,一般需要定义两个版本:一个为非 const 成员并返回引用,另一个为 const 成员并返回 const 引用。 |
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
|
上一页: 第 14.4 节 赋值操作符 返回上级目录: 第十四章 重载操作符与转换 下一页: 第 14.6 节 成员访问操作符
© 2008 woyouxian.net 版权所有 Contact Us