简体   繁体   English

C ++不完全类型的分配

[英]C++ Allocation of incomplete type

I'm tring to create Card and Deck classes but I'm getting an error message that says 我想创建Card和Deck类,但是我收到一条错误消息

Allocation of incomplete type 'Card' 不完全类型'卡'的分配

The problem is happening in Deck::Deck() of Deck.cpp 问题发生在Deck.cpp的Deck :: Deck()中

// //
//Deck.h //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 //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 //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

In the implementation of Deck (ie the Deck.cpp file) you need the full definition of Card to be able to allocate objects of that type. Deck (即Deck.cpp文件)的实现中,您需要Card完整定义才能分配该类型的对象。 So the solution is simply to include Card.h in Deck.cpp . 所以解决方案就是在Deck.cpp包含Card.h

Don't you need to use a "move" operator? 你不需要使用“移动”操作符吗? You can't just push the newly allocated memory onto the stack, it will be deleted by the end of scope. 您不能只将新分配的内存推送到堆栈,它将在范围结束时删除。 I am refering to this: 我在提到这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM