开发者

Reference C++ struct object in another file?

I'm in the process of trying to make a game-in-progress more modular. I'd like to be able to declare a single array of all the room_t objects in the game (room_t rooms[]), store it in world.cpp and call it from other files.

The truncated code below does not work, but it's as far as I've gotten. I think I need to use extern but have not been able to find a method that works correctly. If I try and declare the array in the header file, I get a duplicate object error (as each file calls world.h, I'd assume).

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} }
};


Just add extern room_t rooms[]; in your world.h file.


world.h

extern room_t rooms[];


The problem is that you're trying to reference a variable you've declared in the .cpp file. There's no handle on this outside of the scope of this file. In order to fix this, why not declare the variable in the .h file but have an Init function:

room_t rooms[];
void Init();

Then in the .cpp

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜