在矢量中放置一个类对象?

时间:2010-12-08 18:15:12

标签: c++ class vector

我注意到我可以将一个Class放在一个向量中;这是我的程序,我收到以下错误:

/out:blackjack.exe
blackjack.obj
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

问题出在`blankcard()函数中,我正在尝试创建一个新的类实例,并将其放入向量中。

有人可以阅读代码告诉我我的问题并给我一个如何做到这一点的好例子?谢谢。

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

4 个答案:

答案 0 :(得分:7)

答案 1 :(得分:2)

答案 2 :(得分:1)

您的卡片矢量被定义为静态。这意味着它实际上是您必须定义的全局变量。这可以通过在Card的类定义之后添加以下内容来完成:

std::vector<Card> Card::Cards();

答案 3 :(得分:1)

你必须实际声明你的矢量。