class CFolder; class CMessage { public: CMessage(const string &strMsg = ""); ~CMessage(); CMessage(const CMessage &); CMessage & operator=(const CMessage &rhs); void Save(CFolder &); void Remove(CFolder &); private: void Put_Msg_In_Folders(const set<CFolder*> &); void Remove_Msg_From_Folders(); // 将自身从所有的CFolder集合中删除 private: string m_strMsg; set<CFolder*> m_setFolder; }; class CFolder { public: void AddMsg(CMessage *pMsg); void RemMsg(CMessage *pMsg); private: set<CMessage*> m_setMessage; }; inline void TestMsg() { CFolder f1; CFolder f2; CFolder f3; CMessage msg1("hello"); msg1.Save(f1); msg1.Save(f2); msg1.Save(f3); CMessage msg2 = msg1; // 复制构造函数 CMessage msg3; msg3 = msg2; // 赋值操作符 }
CMessage::CMessage(const string &strMsg /* = "" */):m_strMsg(strMsg) { } CMessage::~CMessage() { Remove_Msg_From_Folders(); } CMessage::CMessage(const CMessage &rhs):m_strMsg(rhs.m_strMsg) ,m_setFolder(rhs.m_setFolder) { Put_Msg_In_Folders(m_setFolder); } CMessage & CMessage::operator=(const CMessage &rhs) { if(this != &rhs) { Remove_Msg_From_Folders(); m_strMsg = rhs.m_strMsg; m_setFolder = rhs.m_setFolder; Put_Msg_In_Folders(rhs.m_setFolder); } return *this; } void CMessage::Put_Msg_In_Folders(const set<CFolder*> &setFolder) { set<CFolder*>::const_iterator itor = setFolder.begin(); while(itor != setFolder.end()) { (*itor)->AddMsg(this); ++itor; } } void CMessage::Remove_Msg_From_Folders() { set<CFolder*>::const_iterator itor = m_setFolder.begin(); while(itor != m_setFolder.end()) { (*itor)->RemMsg(this); ++itor; } } void CMessage::Save(CFolder &rf) { m_setFolder.insert(&rf); } void CFolder::AddMsg(CMessage *pMsg) { m_setMessage.insert(pMsg); } void CFolder::RemMsg(CMessage *pMsg) { set<CMessage*>::iterator itor = m_setMessage.find(pMsg); if(itor != m_setMessage.end()) { m_setMessage.erase(itor); } }
C++ primer 13.4消息处理
最新推荐文章于 2023-01-16 00:00:32 发布