2011-03-22 406 views
1

我正在试图让游戏进行中更模块化。我希望能够声明游戏中所有ro​​om_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} } 
}; 
+1

的extern是你的朋友... – Macmade 2011-03-22 00:52:23

回答

6

只是在你的world.h文件中添加extern room_t rooms[];

+0

我觉得像个白痴。我之前尝试过,它不起作用,因为我把它放在world.h的顶部。不管怎样,谢谢。 – Zomgie 2011-03-22 00:57:10

+1

@Zomgie - 没问题。正如你发现的那样,它确实需要在'struct room_t'类型的定义之后*。 – 2011-03-22 00:58:03

2

world.h

extern room_t rooms[]; 
0

的问题是,你试图引用您在.cpp文件中声明的变量。这个文件的范围之外没有任何处理。为了解决这个问题,为什么不宣布在.h文件中的变量,但有一个初始化函数:在的.cpp

room_t rooms[]; 
void Init(); 

然后

void Init() { 
    // create a room_t and copy it over 
} 
相关问题