Advertisement

Using objects in std::vectors

Started by October 14, 2013 09:20 AM
0 comments, last by BitMaster 11 years, 4 months ago

Hello
I am working on a text-based rpg, using C++ and I have some trouble with std::vectors. I've created a vector in my namespace called "Initialize" , in its header. In "Initialize.cpp" I add objects of the type "Items" to the vector using push_back.

I want to know how I can access the objects in my vector I've created in my namespace "Initialize" from my Item-class.

Example:


GetItemName(Diablo::Initialize::existingItems[1]) //GetItemName returns the name of the object it receives.
                                                  // This doesn't work since I have to include "Initialize.h"
                                                  // which gives linker-errors.

The problem is that if I include "Initialize.h" to be able to access the vector defined in "Initialize.h", i'll get linker-errors since the the vector will be defined both in my "Initialize.h" and in my "Items.cpp".

How can I declare my vector so that I can easily access from other classes etc.?

You cannot just declare any variable in a header file (whether this is a simple int or an std::vector).

You need an extern declaration in the header


// MyFile.h
extern std::vector<MyType> myVariable;
and then the actual declaration in exactly one compilation unit:


// MyFile.cpp
std::vector<MyType> myVariable;
Edit: For the future I would also advise posting the exact errors you getting. It's pretty clear what the problem is now, but in the general case the exact errors are essential.

This topic is closed to new replies.

Advertisement