两个类之间的双向关联
bidirectional association between 2 classes
我想创建两个类之间的双向关联。例如,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
放在头文件中,如果可能的话,不放在任何地方。
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 群集和点之间的关联
- 3个类别之间的关联
- 其中是程序集和cpp代码之间的一对一关联
- 两个类之间的双向关联