2015-04-22 71 views
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->

+1

他們可能不知道?正如你所說他們做同樣的事情。 – DAhrens

+1

是的,沒關係。問你的同事。 – juanchopanza

回答

2

沒有,->風格偏好/知識將是他們會用(* a). VS ->的唯一原因。

6

考慮到一般情況,可能會發生某些迭代器類沒有提供operator ->,而做(*it).x將是唯一可行的方法。另一種可能性是operator *operator ->有一些非標準的語義,並且不可交換。然而,這個類不能滿足任何迭代器的概念,並且在技術上不會是迭代器。

在你的情況下,它是std::list<T>::iterator,其中it->x(*it).x是等效的。

5

此答案的,爲什麼這兩種方法都爲指針存在,如果他們達到相同的背景:https://stackoverflow.com/a/6632474/3113508

你的變化是完全正常的(也可能是由最優選的)的STL迭代器同樣的原因運算符通常首選與指針一起使用。

但是,請注意,一元運算符*->運算符可以重載以在用戶定義的類中提供語義上不同的行爲。因此,潛在地有人可以選擇以不同的方式使用*->,使得foo->bar不再與(*foo).bar相同。確保您熟悉您正在使用的類的文檔。

+0

謝謝!我沒有考慮到操作員重載問題。 – ero1ca

1

的區別在於operator->可以重載與重載operator->返回代理對象的多個級別其所然後再次遞歸Wrapping C++ Member Function Calls by Bjarne Stroustrup施加,直到返回普通指針,等等。

而不能在C++中重載operator.

從紙的例子是:

#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; 
} 

xxyy每個呼叫由一對前綴的括號()/後綴()調用,所以程序製備:

make an X 
make a Y 
prefix f() suffix 
done 
prefix g() suffix 
prefix h() suffix 
+0

確實如此,但*運算符可能會被重載,而在STL迭代器的情況下,無論使用哪種方式,它都會使用運算符重載。 –

+0

@DanKorn'operator *'不是遞歸地應用於它的返回值,與'operator->'不同。 –