use*_*036 3 c++ visual-c++ visual-studio-2012
我想在两个类之间创建双向关联.例如,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 '{'
Run Code Online (Sandbox Code Playgroud)
(我收到这样的错误)
我相信这些错误与我在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
Run Code Online (Sandbox Code Playgroud)
您有一个循环包含依赖项,但在这种情况下,由于类A只包含类B的指针容器,反之亦然,您可以使用前向声明,并将包含在实现文件中.
所以,而不是
#include "account.h"
Run Code Online (Sandbox Code Playgroud)
使用
class Account;
Run Code Online (Sandbox Code Playgroud)
不相关:不要放入using namespace std头文件,如果可能的话,不管.有关该问题的更多信息,请参见此处