C++ primer 13.4消息处理

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);
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值