2

我得到了一些具有以下结构的列表/迭代器的 C++ 代码。

typedef struct{
  int x;
  int y;
}my_struct;

std::list<my_struct> the_list;
std::list<my_struct>::iterator the_iter = the_list.begin();

然后代码以the_iter这种方式访问​​ x 和 y:

(*the_iter).x;
(*the_iter).y;

我想将这些更改为更具可读性的版本:

the_iter->x;
the_iter->y;

从我的 C 角度来看,这对于指针解引用完全没问题。迭代器也是这样吗?我的同事有什么理由会使用(*pointer).而不是p->

4

4 回答 4

6

考虑到一般情况,可能会发生某些迭代器类没有提供的情况operator ->,而做(*it).x将是唯一可能的方法。另一种可能性是,operator *并且operator ->具有一些非标准语义并且不可互换。但是,此类将无法满足任何迭代器概念,并且从技术上讲,它不会是迭代器。

在您的情况下,它是std::list<T>::iterator,it->x(*it).x是等价的。

于 2015-04-22T21:22:43.577 回答
5

这个答案有背景说明为什么这两种方法都存在于指针如果它们实现相同的事情:https ://stackoverflow.com/a/6632474/3113508

对于 STL 迭代器,您的更改将非常好(并且可能是大多数人的首选),原因与->运算符通常首选与指针一起使用的原因相同。

但是,请注意一元运算*符和->运算符可以重载以在用户定义的类中提供语义不同的行为。因此,可能有人可以选择使用*->以不同的方式使用,这样foo->bar就不再与(*foo).bar. 确保您熟悉您正在使用的类的文档。

于 2015-04-22T21:24:05.047 回答
2

不,风格偏好/知识->将是他们使用(* a).vs的唯一原因->

于 2015-04-22T21:20:17.677 回答
1

不同之处在于operator->可以重载以返回具有重载的多个级别的代理对象,operator->然后再次递归地应用它,直到返回一个普通指针,就像Bjarne Stroustrup 的 Wrapping C++ Member Function Calls 中一样。

operator.在 C++ 中不能重载。

该论文中的示例是:

#include<iostream>

using namespace std;

void prefix() { cout<< "prefix"; }
void suffix() { cout<< " suffix\n"; }

template<class T>
class Call_proxy{
  T* p;
public:
  Call_proxy(T* pp) :p(pp){ }
  ˜Call_proxy() { suffix() ; }
  T* operator->() { return p; }
};

template<class T>
class Wrap{
  T* p;
public:
  Wrap(T* pp) :p(pp) { }
  Call_proxy<T> operator->() { prefix() ; return Call_proxy<T>(p) ; }
};

class X{ // one user class
public:
X() { cout<< "make an X\n"; }
  int f() const{ cout<< "f()"; return 1; }
  void g() const{ cout<< "g()"; }
};

class Y{ // another user class
public:
  Y() { cout<< "make a Y\n"; }
  void h() const{ cout<< "h()"; }
};

int main() // simple test code
{
  Wrap<X> xx(new X) ;
  Wrap<Y> yy(new Y) ;
  if(xx->f()) cout<< "done\n";
  xx->g() ;
  yy->h() ;
  return 0;
}

xx对and的每次调用都yy被一对 prefix()/suffix() 调用括起来,所以程序产生了:

make an X
make a Y
prefix f() suffix
done
prefix g() suffix
prefix h() suffix
于 2015-04-22T21:28:48.177 回答