I'm very confused about making a vector to hold classes.
If I wanted to hold a bunch of data in a single vector开发者_Go百科 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);
}
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.
class Card {
public:
Card(int s, int r)
: suit(s), rank(r) {
// Initialize anything else here
}
private:
int suit, rank;
};
Next, define an object which holds a vector
of cards and manipulates them. Let's call it Deck
class Deck {
public:
Deck();
private:
vector <Card> cards;
};
Now, in your Deck
class, you can initialize the collection of cards as you see fit.
Deck::Deck() {
for (int suit = 0; suit < 4; suit++) {
for (int rank = 0; rank < 13; rank++) {
cards.push_back(Card(suit, rank));
}
}
}
There are two simple options here. Closer to what you have written, use an extern
declaration in the header file:
// something.h
extern vector<Card> cards;
// something.cpp
vector<Card> cards;
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 a static
member:
// Card.h
class Card {
// ...
static void init_cards();
static vector<Card> cards;
};
// Card.cpp
vector<Card> Card::cards;
The static
member can be public
or private
like any other member. If it is public
, any code which is not in a Card
method which uses cards
will have to call it Card::cards
.
Either way, you have to figure out how to initialize it with the contents you want....
精彩评论