Sign in to follow this  

Using objects in std::vectors

This topic is 1556 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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. Edited by BitMaster

Share this post


Link to post
Share on other sites
Sign in to follow this