2013-03-10 83 views
3

林想創造2類之間的雙向關聯。例如class Aclass B作爲其私人屬性和class Bclass A作爲其私有屬性。我已經得到了雙向關聯

錯誤主要是:

Error 323 error C2653: 'Account' : is not a class or namespace name 
Error 324 error C2143: syntax error : missing ';' before '{' 

(我得到這樣的錯誤的負載)

我相信這些錯誤得到了與我如何包括paymentMode.h在account.h做,反之亦然。我嘗試評論其中一個類中的一個包含,並且事情工作正常。我可以問,如何刪除這些錯誤,但我仍然可以在帳戶和paymentMode類之間建立雙向關聯?

謝謝!

附上我寫的代碼。

//paymentMode.h 

    #pragma once 
    #ifndef _PAYMENTMODE_H 
    #define _PAYMENTMODE_H 

    #include <string> 
    #include <iostream> 
    #include <vector> 
    #include "item.h" 
    #include "account.h" 

    using namespace std; 

    class PaymentMode 
    { 
    private: 
     string paymentModeName; 
     double paymentModeThreshold; 
     double paymentModeBalance; //how much has the user spent using this paymentMode; 
     vector<Account*> payModeAcctList; 

    public: 
     PaymentMode(string); 
     void pushItem(Item*); 

     void addAcct(Account*); 

     string getPaymentModeName(); 
     void setPaymentModeName(string); 

     void setPaymentModeThreshold(double); 
     double getPaymentModeThreshold(); 

     void setPaymentModeBal(double); 
     double getPaymentModeBal(); 
     void updatePayModeBal(double); 

     int findAccount(string); 
     void deleteAccount(string); 

    }; 

    #endif 



       //account.h 

#pragma once 
#ifndef _ACCOUNT_H 
#define _ACCOUNT_H 

#include <string> 
#include <iostream> 
#include <vector> 
#include "paymentMode.h" 

using namespace std; 

class Account 
{ 
private: 
    string accountName; 
    //vector<PaymentMode*> acctPayModeList; 
    double accountThreshold; 
    double accountBalance; //how much has the user spent using this account. 

public: 
    Account(string); 

    //void addPayMode(PaymentMode*); 
    //int findPayMode(PaymentMode*); 

    string getAccountName(); 
    void setAccountName(string); 

    void setAccountThreshold(double); 
    double getAccountThreshold(); 

    void setAccountBal(double); 
    double getAccountBal(); 
    void updateAcctBal(double); 

}; 

#endif 
+1

[This Q&A](http://stackoverflow.com/questions/14909997/why-arent-my-include-guards-preventing-recursive-inclusion-and-multiple-symbol/14909999#14909999)詳細解釋了什麼是繼續(第一個問題/答案)。 – 2013-03-10 15:39:48

回答

7

你有一個圓形包括相關性,但在這種情況下,由於A類僅持有B類,反之亦然的指針的容器,你可以使用前向聲明,並把包括在執行文件。

所以,與其

#include "account.h" 

使用

class Account; 

無關:不要把using namespace std頭文件,如果可能的話,沒有出路的。有關該問題的更多信息,請參見here

+0

問題解決:)永遠不知道我可以寫類似Account的東西;在頭文件中。謝謝!今天學到了新東西。順便說一下,通過在paymentMode的頭文件中寫入「class Account」,這是否稱爲前向聲明? – user2114036 2013-03-10 15:52:20

+1

@ user2114036,請記住,在C++預處理模式是,'#include'd文件只是複製在其中'#include'出現的地方。在頭文件中,你可以編寫任何你想要的有效C++。甚至可以例如在'#include'd文件中啓動一個語句並在外部結束。 **非常糟糕的味道,但合法的(目前的編譯器可能會警告,它曾經是一個流行的編譯失敗問題......)。 – vonbrand 2013-03-10 17:30:52

+0

@ user2114036是的,這是一個前向聲明。 – juanchopanza 2013-03-10 17:32:22