两个类之间的双向关联

bidirectional association between 2 classes

本文关键字:关联 之间 两个      更新时间:2023-10-16

我想创建两个类之间的双向关联。例如,class A的私有属性为class B, class B的私有属性为class A

我得到的错误主要是:

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

(i get loads of this error)

我认为这些错误与我如何在account.h中包含paymentMode.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

你有一个循环包含依赖,但在这种情况下,因为类a只保存类B的指针容器,反之亦然,你可以使用前向声明,并把包含放在实现文件中。

所以,不用

 #include "account.h"
使用

class Account;

无关:不要将using namespace std放在头文件中,如果可能的话,不放在任何地方。