C ++构造函数数组错误

时间:2016-02-19 00:07:11

标签: c++ arrays constructor

我试图实现一个程序,我应该从一个文本文件中读取输入,该文本格式为字符串,整数,行中的整数,并将这些值存储在数组/向量中。

标题文件:

class Datastructure
{
public:
  Datastructure();
  ~Datastructure();

  int index;

  struct player
  {
    std::string name;
    int bus_number;
    int passenger_number;
  };

  player * player_array = new player[100];
} 

.cpp文件:

Datastructure::Datastructure()
{
    index=0;
}

//Add new players
void Datastructure::add(std::string name, unsigned int brokenBus,
            unsigned int sufferingPeople)
{
    player_array[index].name = name;
    player_array[index].bus_number = brokenBus;
    player_array[index].passenger_number = sufferingPeople;

    //this part works correctly
    std::cout<<player_array[index].name<<","<<player_array[index].bus_number<<","<<
    player_array[index].passenger_number<<std::endl;

    index++;
}

//Print all players
void Datastructure::printLeaderBoard()
{
    for(int i=0;i<100;i++)
        //this part just prints random numbers
        std::cout<<player_array[i].name<<","<<player_array[i].bus_number<<","<<
        player_array[i].passenger_number<<","<<std::endl;
}

这里的问题是,Datastructure::add()函数中的打印在main中运行时可以正常工作。但是,Datastructure::printLeaderBoard()内的打印只会在main中运行时输出随机数。为什么会这样?

0 个答案:

没有答案