为何*itr.getName()无法运行而(*itr).getName()可行?二者差异解析
为什么
*itr.getName()无法运行而(*itr).getName()可以? 先贴出你的代码:
#include <iostream> #include <set> using namespace std; class Example { string name; public: Example(string name) { this->name = name; } string getName() const {return name;} }; bool operator<(Example a, Example b) { return a.getName() < b.getName(); } int main() { set<Example> exp; Example first("first"); Example second("second"); exp.insert(first); exp.insert(second); for(set<Example>::iterator itr = exp.begin(); itr != exp.end(); ++itr) { //cout<<*itr.getName(); - Not working cout<<(*itr).getName()<<endl; } }
两种写法的核心差异是C++运算符优先级:
- 成员访问运算符
.的优先级比解引用运算符*高,所以*itr.getName()会被编译器理解为*(itr.getName())——也就是尝试调用迭代器itr的getName()方法,但set<Example>::iterator并没有这个成员函数,直接触发编译错误。 (*itr).getName()则是先通过*解引用迭代器,得到它指向的Example对象,再调用该对象的getName()方法,完全符合你的逻辑,因此能正常运行。
额外提一句,你还可以用更简洁的写法:itr->getName(),它和(*itr).getName()功能完全等价,->运算符就是专为指针/迭代器设计的语法,会自动完成解引用+成员访问的操作。
内容的提问来源于stack exchange,提问作者sizeof
相关产品推荐
相关产品推荐

