[英]C++ Allocation of incomplete type
我想創建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
在Deck
(即Deck.cpp
文件)的實現中,您需要Card
的完整定義才能分配該類型的對象。 所以解決方案就是在Deck.cpp
包含Card.h
你不需要使用“移動”操作符嗎? 您不能只將新分配的內存推送到堆棧,它將在范圍結束時刪除。 我在提到這個:
cards.push_back(new Card(rank, suit));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.