访问Vector类中的成员变量

时间:2017-04-11 01:09:36

标签: c++

我必须为我的CS课程制作基于文本的RPG。在这个程序中,我必须允许用户输入一个具有特定标签的文件来生成一个世界。我遇到一个问题,我的'room'类的矢量'rooms_f'无法访问我的函数'generate_rooms'中的成员变量。

以下是相关代码:

class room{

public:

  int room_index = 0;
  vector<int> exit_index;
  vector<string> exit_direction;
  vector<bool> exit_locked;
  vector<int> gold;
  vector<int> keys;
  vector<int> potions;
  vector<bool> have_weapon;
  vector<int> weapon_index;
  vector<bool> have_scroll;
  vector<int> scroll_index;
  vector<bool> have_monster;
  vector<int> monster_index;

};


int main() {

  string file_name;           //stores the name of the input file
  ifstream input_file;        //stores the input file
  player character;           //stores your character data
  vector<room> rooms;         //stores data for rooms

  player();

  cout << "\n\n\n\n\nEnter adventure file name: ";
  cin >> file_name;

  input_file.open(file_name.c_str());

  if (input_file.fail()) {
    cerr << "\n\nFailed to open input file.  Terminating program";
    return EXIT_FAILURE;
  }

  cout << "\nEnter name of adventurer: ";
  cin >> character.name;

  cout << "\nAh, " << character.name << " is it?\nYou are about to embark on 
       a fantastical quest of magic\nand fantasy (or whatever you input).  
       Enjoy!";

  generate_rooms(input_file, rooms);

  return EXIT_SUCCESS;

}

void generate_rooms (ifstream& input_file, vector<room>& rooms_f) {

  string read;
  int room_index = -1;
  int direction_index = -1;

  while (!input_file.eof()) {

    room_index += 1;

    input_file >> read;

    if (read == "exit") {

      direction_index += 1;

      input_file >> read;
      rooms_f.exit_index.push_back(read);

      input_file >> read;
      rooms_f.exit_direction.push_back(read);

      input_file >> read;
      rooms_f.exit_locked.push_back(read);

    }

  }

}

给出的编译器错误是:

prog6.cc: In function ‘void generate_rooms(std::ifstream&, 
std::vector<room>&)’:
prog6.cc:168:15: error: ‘class std::vector<room>’ has no member named 
‘exit_index’
       rooms_f.exit_index.push_back(read);
               ^
prog6.cc:171:15: error: ‘class std::vector<room>’ has no member named 
‘exit_direction’
       rooms_f.exit_direction.push_back(read);
               ^
prog6.cc:174:15: error: ‘class std::vector<room>’ has no member named 
‘exit_locked’
       rooms_f.exit_locked.push_back(read);
               ^

1 个答案:

答案 0 :(得分:1)

rooms_f是房间的向量,但在您可以访问该向量中特定房间的字段之前,您必须选择一个房间。您错过了在向量索引处访问项目的步骤。

vector<room>[index].field_name

您还需要初始化房间对象,然后才能使用它们。