2016-12-02 69 views
0

我遇到了一個循環包含引用錯誤,我希望在CardFactory中使用Deck類型的對象,並在Deck中使用CardFactory類型的對象。有關如何解決這個問題的任何提示?在C++頭文件中解析循環引用

//CardFactory.h 
#ifndef CARDFACTORY_H 
#define CARDFACTORY_H 

#include "Deck.h" 

#include <string> 

using std::string; 

class CardFactory { 

public: 
    Deck getDeck(); 
    static CardFactory* getFactory() { 
     static CardFactory singleton; 
     return &singleton; 
    } 

}; 

#endif 

//Deck.h 
#ifndef DECK_H 
#define DECK_H 

#include <vector> 
#include <iostream> 
#include "CardFactory.h" 
using std::ostream; 

class Deck : public std::vector<Card*> { 
    friend ostream& operator<<(ostream& os, const Deck& dt); 
    Card* draw(); 
    Deck(CardFactory* cf); 
}; 

#endif 
+0

類不應從載體和其他STL容器繼承。 – 2016-12-02 03:59:51

回答

2

正向參考(或前向聲明)。

Deck.h你不需要#include "CardFactory.h",而不只是聲明類。

class CardFactory; 

這應該工作,因爲在Deck類,你只使用指針CardFactory

+0

也稱爲「前向聲明」 –

+0

@MichaelAlbers是真的 – artm