C ++不完全类型的分配

时间:2013-08-15 11:25:37

标签: c++ allocation

我要创建Card和Deck类但我收到一条错误消息

分配不完整类型'卡'

问题发生在Deck.cpp的Deck :: Deck()

//
//Deck.h

#ifndef JS_DECK_H
#define JS_DECK_H

#include <iostream>
using std::cout;

#include <vector>
using std::vector;

//forward declaration
class Card;

namespace JS {
    class Deck {

    public:
        Deck();
    private:
        vector<Card *>cards;
    };

}

#endif

//
//Deck.cpp

#include "Deck.h"

using namespace JS;

Deck::Deck(){

    for(int suit = 0; suit < 4; suit++){
        for(int rank = 1; rank < 14; rank++){

            cards.push_back(new Card(rank, suit));//allocation of incomplete type 'Card'
        }
    }
}

//
//Card.h

#ifndef JS_CARD_H
#define JS_CARD_H

#include <ostream>
using std::ostream;

#include <string>
using std::string;

#include <vector>
using std::vector;

namespace JS {
    class Card {

    friend ostream &operator<<(ostream &out, const Card &rhs);

    public:
        enum Suit { DIAMONDS, HEARTS, SPADES, CLUBS };
        enum Rank { ACE = 1, JACK = 11, QUEEN = 12, KING = 13 };

        Card(int rank, int suit) : rank(rank), suit(suit){}

        string getRank() const;
        string getSuit() const;
        int getRankValue() const;

        int operator+(const Card& rhs);
        void displayCard(const Card &rhs);

    private:
        int rank;
        int suit;
    };

}

#endif

2 个答案:

答案 0 :(得分:8)

Deck(即Deck.cpp文件)的实现中,您需要Card完整定义才能分配该类型的对象。因此,解决方案只是在Card.h中包含Deck.cpp

答案 1 :(得分:0)

您不需要使用“移动”操作符吗?您不能只将新分配的内存推送到堆栈,它将在范围结束时删除。我在提到这个:

cards.push_back(new Card(rank, suit));