设为首页 加入收藏

TOP

5.6 The Arrow Operator
2013-10-07 15:24:21 来源: 作者: 【 】 浏览:68
Tags:5.6 The Arrow Operator

箭头操作符要求操作数是个指针或类似指针的东西(迭代器或智能指针)。

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:

  1. 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:

  1. Sales_item *sp = &item1;  
  2. (*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:

  1. // run the same_isbn member of sp then dereference the result!  
  2. *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

  1. *(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:

  1. (*p).foo; // dereference p to get an object and fetch its member named foo  
  2. 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

  1. 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.

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.

(a) *iter++; (b) (*iter)++;

(c) *iter.empty() (d) iter->empty();

(e) ++*iter; (f) iter++->empty();

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.7 The Conditional Operator 下一篇2.3.3 Defining Objects (2)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Sphinx : 高性能SQL (2025-12-24 10:18:11)
·Pandas 性能优化 - (2025-12-24 10:18:08)
·MySQL 索引 - 菜鸟教 (2025-12-24 10:18:06)
·Shell 基本运算符 - (2025-12-24 09:52:56)
·Shell 函数 | 菜鸟教 (2025-12-24 09:52:54)