代码改变世界

消息类和消息所在的目录类....

2012-04-29 12:59  javaspring  阅读(150)  评论(0编辑  收藏  举报
#ifndef MESSAGE_H
#define MESSAGE_H

#include <iostream>
#include <set>

class Message;

class Folder
{
public:
	Folder(){}
	Folder(const Folder& f);

	Folder& operator=(const Folder& rhs);
	~Folder();
    
	void save(Message& m);
	void remove(Message& m);

	void remMes(Message* m);
    void addMes(Message* m);

private:
	std::set<Message*> messages;
	void put_folder_in_msgs(const std::set<Message*>& rhs);
    void rem_folder_from_msgs();
};



class Message
{
public:
	Message(const std::string& str="")
		:contents(str){}

	Message::Message(const Message& rhs);

	Message& operator=(const Message& rhs);
	~Message();
	void save(Folder& f);
	void remove(Folder& f);
	void addfolder(Folder* f);
	void remfolder(Folder* f);
private:
	std::string contents;
	std::set<Folder*> folders;
	void put_msg_in_Folders(const std::set<Folder*>& rhs);

	void remove_msg_form_folders();
};



    Folder::Folder(const Folder& f)
		:messages(f.messages)
	{

	}
	Folder& Folder::operator=(const Folder& rhs)
	{
		if (&rhs!=this)
		{
			rem_folder_from_msgs();
			messages=rhs.messages;
			put_folder_in_msgs(rhs.messages);
		}
		return *this;
	}
	Folder::~Folder()
	{
		rem_folder_from_msgs();
	}

	void Folder::save(Message& m)
	{
		addMes(&m);
		m.addfolder(this);
	}
	void Folder::remove(Message& m)
	{
		remMes(&m);
		m.remfolder(this);
	}

	void Folder::remMes(Message* m)
	{
		messages.insert(m);
	}
	void Folder::addMes(Message* m)
	{
		messages.erase(m);
	}


	void Folder::put_folder_in_msgs(const std::set<Message*>& rhs)
	{
		for (std::set<Message*>::const_iterator it=rhs.begin();it!=rhs.end();it++)
		{
			(*it)->addfolder(this);
		}
	}
	void Folder::rem_folder_from_msgs()
	{
		for (std::set<Message*>::const_iterator it=messages.begin();it!=messages.end();it++)
		{
			(*it)->remfolder(this);
		}
	}



	Message::Message(const Message& rhs)
		:contents(rhs.contents),folders(rhs.folders)
	{
		put_msg_in_Folders(folders);
	}

	Message& Message::operator=(const Message& rhs)
	{
		if (&rhs!=this)
		{
			remove_msg_form_folders();
			contents=rhs.contents;
			folders=rhs.folders;
			put_msg_in_Folders(rhs.folders);
		}
		return *this;
	}
	Message::~Message()
	{
		remove_msg_form_folders();
	}
	void Message::save(Folder& f)
	{
		addfolder(&f);
		f.addMes(this);
	}
	void Message::remove(Folder& f)
	{
		remfolder(&f);
        f.remMes(this);
	}
	void Message::addfolder(Folder* f)
	{
		folders.insert(f);
	}
	void Message::remfolder(Folder* f)
	{
		folders.erase(f);
	}

	void Message::put_msg_in_Folders(const std::set<Folder*>& rhs)
	{
		for (std::set<Folder*>::const_iterator beg=rhs.begin();beg!=rhs.end();beg++)
		{
			(*beg)->addMes(this);
		}
	}

	void Message::remove_msg_form_folders()
	{
		for (std::set<Folder*>::const_iterator beg=folders.begin();beg!=folders.end();beg++)
		{
			(*beg)->remMes(this);
		}
	}


#endif