调用对象矢量的成员函数

时间:2013-09-16 00:18:18

标签: c++ vector iterator

所以我有一个像这样声明的向量:

vector <Game *> games;

我在Game类中有一个函数,如:

public:

    // Rest of .h

    void hello(){
        cout << "hello" << endl;
    }

我正在尝试使用迭代器迭代我的games向量,并且每次都调用hello()函数:

vector <Game *>::const_iterator it_games = games.begin();

for (it_games = games.begin(); it_games != games.end(); it_games++) {
    *it_games->hello();
}

但是当我尝试编译时,我不断收到此错误:

main.cpp: In function ‘void summary(std::vector<Game*, std::allocator<Game*> >, std::string, std::string, std::string, std::string)’:
main.cpp:56: error: request for member ‘hello’ in ‘* it_games. __gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> [with _Iterator = Game* const*, _Container = std::vector<Game*, std::allocator<Game*> >]()’, which is of non-class type ‘Game* const’

知道发生了什么/如何获得我想要的功能?

2 个答案:

答案 0 :(得分:2)

operator*的优先级低于operator->。所以这个:

*it_games->hello();

应该是这样的:

(*it_games)->hello();

答案 1 :(得分:2)

->具有优先权,因此在hello()之前不会取消引用it_games指针。

更改

*it_games->hello();

(*it_games)->hello();