设计一个名为Message和一个Folder的类。
体现拷贝构造函数,拷贝赋值运算符的作用。
注意:
1.两个类在实现过程中需要相互调用时,头文件的包含。
2.工具函数的使用。
//in _Folder.h
#ifndef FOLDER_H
#define FOLDER_H
#include"_Message.h" //*****************It's necessary************
#include<iostream>
#include<set>
using namespace std;
class Message; //****************It's necessary*******************
class Folder //define class Folder
{
friend class Message;
public:
Folder() //default constructor
{
//empty body
}
void addMsg(Message *m); //insert a message into this folder
void rmMsg(Message *m); //remove a message from this folder
void display() const; //show all messages contented in this folder
private:
set<Message *> messages;
};
#endif // FOLDER_H
//in _Folder.cpp
#include"_Folder.h"
#include<iostream>
using namespace std;
void Folder::addMsg(Message *m) //insert a message into this folder
{
messages.insert(m);
}
void Folder::rmMsg(Message *m) //remove a message from this folder
{
messages.erase(m);
}
void Folder::display() const //show all messages contented in this folder
{
cout << "these message are contented in this folder:\n";
for (auto &m : messages)
m->display();
}
//in _Message.h
#ifndef MESSAGE_H
#define MESSAGE_H
#include"_Folder.h" //******************It's necessary***************
#include<iostream>
#include<string>
#include<set>
using namespace std;
class Folder; //************It's necessary**********
class Message
{
friend class Folder;
public:
Message(const string &s = string())
:contents(s)
{
//empty body
};
Message(const Message &m) //copy constructor
:contents(m.contents), folder(m.folder)
{
add_to_folder(m);
}
Message &operator=(const Message &m); //overload '='
~Message(); //destructor
void save(Folder &f); //add this message to a folder
void remove(Folder &f); //remove this message from a folder
void display() const;
private:
string contents;
set<Folder *> folder;
void add_to_folder(const Message &m); //utility function
void remove_from_Folder(); //utility function
};
#endif // MESSAGE_H
//in _Message.cpp
#include"_Message.h"
#include<iostream>
using namespace std;
void Message::save(Folder &f) //add this message to a folder
{
folder.insert(&f);
f.addMsg(this);
}
void Message::remove(Folder &f) //remove this message from a folder
{
f.rmMsg(this);
folder.erase(&f);
}
void Message::display() const
{
cout << contents << endl;
}
void Message::add_to_folder(const Message &m)
{
for (auto f : m.folder)
f->addMsg(this);
}
void Message::remove_from_Folder()
{
for (auto f : folder)
f->rmMsg(this);
}
Message &Message::operator=(const Message &m)
{
remove_from_Folder();
contents = m.contents;
folder = m.folder;
add_to_folder(m);
}
Message::~Message()
{
remove_from_Folder();
}