Zom*_*gie 1 c++ variables struct extern
我正在努力让正在进行的游戏更加模块化.我希望能够在游戏中声明所有room_t对象的单个数组(room_t rooms []),将其存储在world.cpp中并从其他文件中调用它.
下面的截断代码不起作用,但就我所知.我想我需要使用extern但是无法找到一个正常工作的方法.如果我尝试在头文件中声明数组,我会得到一个重复的对象错误(因为每个文件都调用world.h,我假设).
main.cpp中
#include <iostream>
#include "world.h"
int main()
{
int currentLocation = 0;
cout << "Room: " << rooms[currentLocation].name << "\n";
// error: 'rooms' was not declared in this scope
cout << rooms[currentLocation].desc << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
world.h
#ifndef WORLD_H
#define WORLD_H
#include <string>
const int ROOM_EXIT_LIST = 10;
const int ROOM_INVENTORY_SIZE = 10;
struct room_t
{
std::string name;
std::string desc;
int exits[ROOM_EXIT_LIST];
int inventory[ROOM_INVENTORY_SIZE];
};
#endif
Run Code Online (Sandbox Code Playgroud)
world.cpp
#include "world.h"
room_t rooms[] = {
{"Bedroom", "There is a bed in here.", {-1,1,2,-1} },
{"Kitchen", "Knives! Knives everywhere!", {0,-1,3,-1} },
{"Hallway North", "A long corridor.",{-1,-1,-1,0} },
{"Hallway South", "A long corridor.",{-1,-1,-1,1} }
};
Run Code Online (Sandbox Code Playgroud)