向量对象的指针

时间:2017-11-27 06:44:00

标签: c++

我希望它的向量指向对象(类名称为ScoreKeeper。我的目标是存储玩家的名字和分数,并将它们写入文件。在这种情况下,我的问题是:你如何访问对象&#39 ; s数据成员。这是我的代码。

包括" std_lib_facilities_5.h"

class ScoreKeeper {

public:

    // Variables
    int Score;
    string Name;

    // Functions
    void SetScore(int number)
    {
        Score = number;
        return;
    }
    void SetName( string name)
    {
        Name = name;
        return;;
    }

    ScoreKeeper( int nn = 0, string ss =" "): Score(nn), Name(ss){}                 // Constructor
    ~ScoreKeeper() {};                                                              // Destructor
    friend ostream& operator<< (ostream &out, const ScoreKeeper &player);

};
//----------------------------------------------------------------------------------
ostream& operator<<(ostream& os, const ScoreKeeper& player){
    os << player.Name << " " << player.Score;
    return os;
}
//----------------------------------------------------------------------------------

int main() {

    vector<ScoreKeeper*> Players;

    ScoreKeeper Player1 = new ScoreKeeper;
    ScoreKeeper Player2 = new ScoreKeeper;

    Player1->SetScore(300);
    Player1->SetName("Pape");

    Player2->SetScore(200);
    Player2->SetName("Yamadou");

    Players.push_back(Player1);
    Players.push_back(Player1);

    //--------------------------------------------------------------------------------

    for(int i = 0; i < 2; ++i){
        cout << "Player: " << Players[i]->Name << " " << Players[i]->Score << endl;
    }
    //--------------------------------------------------------------------------------

    ofstream ost {"mydata.txt"};

    if(!ost) error("can't open output file ", "mydata.txt");

    for(int i = 0; i < Players.size(); ++i){
        ost << Players[i].Name << " " << Players[i].Score << endl;
    }
    ost.close();

}

1 个答案:

答案 0 :(得分:0)

您还没有提到您遇到的错误。从我看到的,你有一个存储指向ScoreKeeper类的指针的向量。 new运算符返回指针引用,您的代码应该从

更改
ScoreKeeper Player1 = new ScoreKeeper;
ScoreKeeper Player2 = new ScoreKeeper;

ScoreKeeper* Player1 = new ScoreKeeper;
ScoreKeeper* Player2 = new ScoreKeeper;

当你从矢量中读取时,使用&#34; - &gt;&#34;而不是&#34;。&#34;操作