Placing a class object inside a vector?
I noticed that I can place a Class inside a vector; here is my program, where I am receiving the following error:
/out:blackjack.exe
blackjack.ob开发者_JAVA技巧j
blackjack.obj : error LNK2019: unresolved external symbol "private: static class
std::vector<class Card,class std::allocator<class Card> > Card::Cards" (?Cards@
Card@@0V?$vector@VCard@@V?$allocator@VCard@@@std@@@std@@A) referenced in functio
n "public: static void __cdecl Card::blankCard(void)" (?blankCard@Card@@SAXXZ)
blackjack.exe : fatal error LNK1120: 1 unresolved externals
The issue is inside the `blankcard() function, where I'm trying to create a new class instance, and put it into the vector.
Can someone please read the code tell me my issue and give me a good example in how to do this? Thank you.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Card
{
private:
string suit;
int number;
static vector<Card> Cards;
public:
Card::Card();
Card::Card(string cardS, int cardV);
static void createCards();
static void blankCard();
};
int main()
{
Card::blankCard();
return 0;
}
Card::Card(){};
Card::Card(string cardS, int cardV){};
void Card::blankCard()
{
int temp = 1;
int cardValue;
string suit;
int suitCount = 1;
for(int i = 1; i < 52; i++)
{
if(temp == 1 || temp > 13)
{
temp = 1;
cardValue = temp;
temp ++;
}
else if(temp > 1)
{
cardValue = temp;
temp ++;
}
if(suitCount <= 13)
{
suit = "spade";
suitCount++;
}
else if( suitCount >= 14 && suitCount <= 26)
{
suit = "club";
suitCount++;
}
else if(suitCount >= 27 && suitCount <= 39)
{
suit = "heart";
suitCount++;
}
else if(suitCount >= 40 && suitCount <= 52)
{
suit = "diamonds";
suitCount++;
}
Card a = Card(suit, cardValue);
Cards.push_back(a);
}
}
You are declaring the static member Cards
inside the class definition, but you aren't defining it anywhere. Add a definition after the class definition:
vector<Card> Card::Cards;
You'll have to instantiate the vector somewhere as it's a static. Basically, you want something like:
std::vector<Card> Card::Cards;
somewhere in your code.
Your cards vector is defined as static. That means it is effectively a global variable that you must define. This can be done by putting the following after the class definition of Card
:
std::vector<Card> Card::Cards();
You have to actually declare your vector.
精彩评论