2011-03-22 4 views
1

저는 게임 진행 중 모듈화를 시도하는 중입니다. 나는 room_t 객체들 (room_t rooms [])에있는 모든 room_t 객체들의 단일 배열을 선언하고 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

#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

통근이 당신의 친구입니다 – Macmade

답변

6

은 그냥 world.h 파일에 extern room_t rooms[];을 추가

#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.

extern room_t rooms[]; 
+0

를 통화 당에서 그런

room_t rooms[]; void Init(); 

:이 문제를 해결하기 위해, 왜 .H 파일의 변수를 선언하지 않지만 초기화 기능이 바보처럼. 나는 전에 그것을 시도하고 그것이 world.h의 맨 위에 놓았 기 때문에 작동하지 않았다. 어쨌든, 고마워. – Zomgie

+1

@Zomgie - 문제 없습니다. 알았 듯이'struct room_t' 타입의 정의가 * * 필요합니다. –

2

world.h 당신이 .cpp 파일에 선언 한 변수를 참조하기 위해 노력하고 있다는 점이다. 이 파일의 범위를 벗어난 핸들은 없습니다. 내가 느끼는 ...

void Init() { 
    // create a room_t and copy it over 
} 
0

문제