Team LiB
Previous Section Next Section

5.6. The Arrow Operator

5.6. 箭头操作符

The arrow operator (->) provides a synonym for expressions involving the dot and dereference operators. The dot operator (Section 1.5.2, p. 25) fetches an element from an object of class type:

C++ 语言为包含点操作符和解引用操作符的表达式提供了一个同义词:箭头操作符(->)。点操作符(第 1.5.2 节)用于获取类类型对象的成员:

     item1.same_isbn(item2); // run the same_isbn member of item1

If we had a pointer (or iterator) to a Sales_item, we would have to dereference the pointer (or iterator) before applying the dot operator:

如果有一个指向 Sales_item 对象的指针(或迭代器),则在使用点操作符前,需对该指针(或迭代器)进行解引用:

     Sales_item *sp = &item1;
     (*sp).same_isbn(item2); // run same_isbn on object to which sp points

Here we dereference sp to get the underlying Sales_item. Then we use the dot operator to run same_isbn on that object. We must parenthesize the dereference because dereference has a lower precedence than dot. If we omit the parentheses, this code means something quite different:

这里,对 sp 进行解引用以获得指定的 Sales_item 对象。然后使用点操作符调用指定对象的 same_isbn 成员函数。在上述用法中,注意必须用圆括号把解引用括起来,因为解引用的优先级低于点操作符。如果漏掉圆括号,则这段代码的含义就完全不同了:

     // run the same_isbn member of sp then dereference the result!
     *sp.same_isbn(item2); // error: sp has no member named same_isbn

This expression attempts to fetch the same_isbn member of the object sp. It is equivalent to

这个表达式企图获得 sp 对象的 same_isbn 成员。等价于:

     *(sp.same_isbn(item2));  // equivalent to *sp.same_isbn(item2);

However, sp is a pointer, which has no members; this code will not compile.


Because it is easy to forget the parentheses and because this kind of code is a common usage, the language defines the arrow operator as a synonym for a dereference followed by the dot operator. Given a pointer (or iterator) to an object of class type, the following expressions are equivalent:

因为编程时很容易忘记圆括号,而且这类代码又经常使用,所以 C++ 为在点操作符后使用的解引用操作定义了一个同义词:箭头操作符(->)。假设有一个指向类类型对象的指针(或迭代器),下面的表达式相互等价:

     (*p).foo; // dereference p to get an object and fetch its member named foo
     p->foo;   // equivalent way to fetch the foo from the object to which p points

More concretely, we can rewrite the call to same_isbn as

具体地,可将 same_isbn 的调用重写为:

     sp->same_isbn(item2); // equivalent to (*sp).same_isbn(item2)

Exercises Section 5.6

Exercise 5.18:

Write a program that defines a vector of pointers to strings. Read the vector, printing each string and its corresponding size.

编写程序定义一个 vector 对象,其每个元素都是指向 string 类型的指针,读取该 vector 对象,输出每个 string 的内容及其相应的长度。

Exercise 5.19:

Assuming that iter is a vector<string>::iterator, indicate which, if any, of the following expressions is legal. Explain the behavior of the legal expressions.

假设 itervector<string>::iterator 类型的变量,指出下面哪些表达式是合法的,并解释这些合法表达式的行为。

     (a) *iter++;         (b) (*iter)++;
     (c) *iter.empty()    (d) iter->empty();
     (e) ++*iter;         (f) iter++->empty();
Team LiB
Previous Section Next Section