2017-04-11 62 views
1

我必须为我的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); 
      ^
+0

这就像错误说的。 'rooms_f'是'vector',而不是'room',所以它没有'exit_index'成员。你想一次建造一个'房间',然后将它添加到'rooms_f'? – aschepler

回答

1

rooms_f是房间的载体,但在此之前,你可以访问某个特定的房间领域矢量,你必须选择一个房间。您错过了在矢量索引处访问项目的步骤。

vector<room>[index].field_name 

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