C++ Primer : 第十三章 : 拷贝控制示例

/* Message.h */

#ifndef _MESSAGE_H_
#define _MESSAGE_H_

#include <iostream>
#include <string>
#include <set>

class Folders;

class Message {
	friend class Folders;

public:
	// Default Constructor
	explicit Message (const std::string& str = "") : contests (str){}
	// Copy Constructor
	Message(const Message&);
	// Copy Assignment function
	Message& operator = (const Message&);

	// add this Messageto a Folder or remove from this Message from Folder
	void save (Folders&);
	void remove (Folders&);
	
	void swap (Message&, Message&);

	std::string& getMsgName (){ return contests; }

	~Message ();

private:

	std::string contests; // message

	std::set<Folders*> folders; // save the folders that include this message

	void add_to_Folders (const Message&);
	void remove_from_Folders ();

};

#endif // _MESSAGE_H_


/* Message.cpp */

#include "Message.h"

// Copy Constructor
Message::Message (const Message& msg) : contests (msg.contests), folders (msg.folders){

	add_to_Folders(msg);
}

Message::~Message (){

	remove_from_Folders();
}

// Copy Assignment
Message& Message::operator=(const Message& msg){

	remove_from_Folders();
	contests = msg.contests;
	folders  = msg.folders;
	add_to_Folders(msg);
	return *this;
}

void Message::save (Folders& f){

	folders.insert(&f);
	f.addMsg(this);
}

void Message::remove (Folders& f){

	folders.erase (&f);
	f.removeMsg(this);
}

inline
void Message::add_to_Folders (const Message& msg){

	for (auto f : msg.folders)
		f->addMsg(this);
}

inline
void Message::remove_from_Folders (){

	for (auto f : folders)
		f->removeMsg(this);

}

/* Folders.h */

#ifndef _FOLDERS_H_
#define _FOLDERS_H_

#include <string>
#include <set>

class Message;

class Folders {

	friend class Message;
public:

	explicit Folders (const std::string& fld = "") : folderName (fld){}
	~Folders ();

	Folders (const Folders&);

	Folders& operator = (const Folders&);
	
	void addToMsg (const Folders&);
	void rmFromMsg ();

	// 
	void addMsg (Message*);
	void removeMsg (Message*);

	std::string& getFldName (){ return folderName; }

private:

	std::string folderName;

	std::set<Message*> message;
};

#endif // _FOLDERS

#include "Folders.h"


Folders::Folders (const Folders& f) : folderName(f.folderName), message(f.message){

	addToMsg(f);

}

Folders::~Folders (){

	rmFromMsg();

}

Folders& Folders::operator=(const Folders& f){

	rmFromMsg();
	folderName  = f.folderName;
	message		= f.message;
	addToMsg(f);
	return *this;
}

void Folders::addToMsg (const Folders& fld){

	for (auto m : fld.message)
		m->save (*this);

}

void Folders::rmFromMsg (){

	for (auto m : message)
		m->remove(*this);

}

void Folders::addMsg (Message* msg){

	message.insert(msg);
	
}

void Folders::removeMsg (Message* msg){

	message.erase (msg);
}


相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页