我想在两个类之间创建一个双向关联。例如,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 '{'
(我得到了很多这样的错误)
我认为这些错误与我在account.h中包含paymentMode.h的方式有关,反之亦然。我试着注释掉其中一个类中的一个包含项,结果一切正常。我可以问一下如何在account和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
发布于 2013-03-10 15:40:19
您有一个循环include依赖项,但在本例中,由于类A仅包含类B的指针容器,反之亦然,因此您可以使用转发声明,并将includes放入实现文件中。
因此,不是
#include "account.h"
使用
class Account;
无关:不要将using namespace std
放在头文件中,如果可能,不要放在任何地方。有关该问题的更多信息,请参阅here。
https://stackoverflow.com/questions/15324009
复制相似问题