我正在试图让游戏进行中更模块化。我希望能够声明游戏中所有room_t对象的单个数组(room_t rooms []),并将其存储在world.cpp中并从其他文件中调用它。在另一个文件中引用C++ struct对象?
下面的截断代码不起作用,但它是我得到的。我想我需要使用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;
}
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
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} }
};
的extern是你的朋友... – Macmade 2011-03-22 00:52:23