访问向量类中的成员变量
Accessing Member Variables in Vector Class
我必须为我的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
您还需要先初始化房间对象,然后才能使用它们。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查