2011-03-22 417 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 
} 
相關問題