2013-03-10 85 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