我正在試圖讓遊戲進行中更模塊化。我希望能夠聲明遊戲中所有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