访问向量类中的成员变量

Accessing Member Variables in Vector Class

本文关键字:成员 变量 向量 访问      更新时间:2023-10-16

我必须为我的CS类制作一个基于文本的RPG。 在这个程序中,我必须允许用户输入具有特定标签的文件来生成世界。 我遇到了一个问题,我的类"房间"的向量"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 << "nnnnnEnter adventure file name: ";
  cin >> file_name;
  input_file.open(file_name.c_str());
  if (input_file.fail()) {
    cerr << "nnFailed 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 magicnand 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);
               ^

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

vector<room>[index].field_name

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