迭代一个接受类的向量

时间:2013-08-06 11:49:38

标签: class stl constructor destructor superclass

以下是我当前代码的3部分。当我尝试迭代我的向量并取消引用“compare”方法时,我的main.cpp文件中出现错误。有人可以帮我找出造成这个错误的原因吗?

Main.cpp的:

#include <iostream>
#include <vector>
#include "Scores.h"

using namespace std;

int main()
{
    vector<comparable*> comparables;

    for(int i = 0; i < 5; i++)
    {
        comparables.push_back(new Player());
    }

    for(vector<comparable*>::iterator itr = comparables.begin(), end = comparables.end(); itr != end ; itr++ )
    {
        (itr*)->compare(); ****THIS IS THE LINE WHERE THE ERROR OCCURS****************
    }

    cout << "Mission Accomplished!\n\n";

    return 0;
}

我得到错误:错误:期望')'令牌之前的primary-expression。 我无法弄清楚。顺便说一下,这就是改变后的代码的样子。

Scores.cpp:

#include <iostream>
#include "Scores.h"
#include <string>

using namespace std;

void Player::compare()
{
    cout << "comparing" << '\n';
}

Player::Player()
{
   getname();
   getscore();
}

void Player::getscore()
{
    cout << "Enter score: ";
    cin >> player_score;
}

void Player::getname()
{
    cout << "Enter Name: ";
    cin >> player_name;
}

头文件(Scores.h)

#ifndef SCORES_H_INCLUDED
#define SCORES_H_INCLUDED

class comparable
{
    public:

    virtual void compare() = 0;

};

class Player: public comparable
{
    public:

    Player();
    void compare();
    void getscore();
    void getname();

    private:
    std::string player_name;
    int player_score;
};


#endif // SCORES_H_INCLUDED

1 个答案:

答案 0 :(得分:0)

如何替换

for(vector<comparable*>::iterator itr = comparables.begin(), end = comparables.end(); itr != end ; itr++ )
{
    (itr*)->compare(); ****THIS IS THE LINE WHERE THE ERROR OCCURS****************
}

通过

for(vector<comparable*>::iterator itr = comparables.begin(), end = comparables.end(); itr != end ; itr++ )
{
    (*itr)->compare(); // THIS WAS THE LINE WHERE THE ERROR USED TO OCCUR :)
}