简体   繁体   中英

iterator dereferencing issue

if I have

list<NS*> v;  
typename list<NS*>::iterator it;   
for(it = v.begin();it!=v.end();++it){  
  cout<<**it.ns_member1<<endl;    // does not compile  
  NS ns = **it;  
  cout<<ns.ns_member1<<endl;      // this compiles.  
}

Why so?

Try (**it).ns_member1 .

Otherwise, the dereferencing would be done after trying to evaluate it.ns_member1 . It's like 3*(1+2) vs 3*1+2 .

Dereference (the '*') has a lower precedence than the '.' operator, so this line:

cout<<**it.ns_member1<<endl;

Works out like this:

cout << (**(it.ns_member1)) <<endl; // ERROR

I would suggest doing it like this:

cout << (*it)->ns_member1 << endl;

There is really no need to use the dereference operator twice, once followed by the '->' operator will do the same thing and should read clearer to most people.

HTH.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM