I want to create a Vector to hold classes

2019-08-15 08:57发布

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);
} 

标签: c++ class vector
2条回答
Evening l夕情丶
2楼-- · 2019-08-15 09:13

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

查看更多
相关推荐>>
3楼-- · 2019-08-15 09:21

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));
    }
  }
}
查看更多
登录 后发表回答