Im very confused about making a vector to hold classes. if i wanted to hold a bunch of data in a single vector like the example below. then have the data written in a class member function, and able to be called out and used by other functions.
where do i stick the vector declaration? please help!
#include <vector>
class Card
{
public:
int suit;
int rank;
Card::Card(int suit, int rank);
Function();
};
vector<Card> cards;
int main()
{
}
Card::Function()
{
for loop...
Card cardz(i, i);
cards.push_back(cardz);
}
There are two simple options here. Closer to what you have written, use an
extern
declaration in the header file:Or if it makes sense for this vector to "belong" to
class Card
(but there's still only one of them), you can make it astatic
member:The
static
member can bepublic
orprivate
like any other member. If it ispublic
, any code which is not in aCard
method which usescards
will have to call itCard::cards
.Either way, you have to figure out how to initialize it with the contents you want....
It seems to me that you're stretching the bounds of what a
Card
object should do. May I suggest the following layout? First defines a single card.Next, define an object which holds a
vector
of cards and manipulates them. Let's call itDeck
Now, in your
Deck
class, you can initialize the collection of cards as you see fit.