Jump to content

  • Log In with Google      Sign In   
  • Create Account


Using objects in std::vectors


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 Ferazu   Members   -  Reputation: 173

Like
0Likes
Like

Posted 14 October 2013 - 03:20 AM

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



Sponsor:

#2 BitMaster   Crossbones+   -  Reputation: 3658

Like
0Likes
Like

Posted 14 October 2013 - 05:23 AM

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, 14 October 2013 - 05:24 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS