1 #include<string> 2 #include<iostream> 3 #include<set> 4 class Folder; 5 class Message; 6 7 class Folder 8 { 9 public: 10 void delete_mess(Message* pmess) 11 { 12 messages.erase(pmess); 13 } 14 void add_mess(Message* pmess) 15 { 16 messages.insert(pmess); 17 } 18 ~Folder(); // 在这里定义函数会说message类没定义。要放在外面。 19 /* { 20 // 对于每个message 要删除指向他的folder 21 for(std::set<Message*>::iterator it = messages.begin(); it != messages.end(); ++it) 22 (*it)->delete_folder(this); 23 std::cout << "~Folder" << std::endl; 24 }*/ 25 26 private: 27 std::set<Message*> messages; 28 }; 29 30 31 class Message 32 { 33 public: 34 Message(std::string str = ""):contents(str){} 35 Message(const Message& mes); 36 Message& operator=(const Message& mes); 37 ~Message(); 38 void add_folder(Folder& fo) 39 { folders.insert(&fo);fo.add_mess(this);} 40 void delete_folder(Folder* fo) 41 { folders.erase(fo); (*fo).delete_mess(this);} 42 private: 43 std::string contents; 44 std::set<Folder*> folders; 45 }; 46 47 48 Message::Message(const Message& mes):contents(mes.contents),folders(mes.folders) 49 { 50 51 for(std::set<Folder*>::iterator it = folders.begin(); it != folders.end(); ++it) 52 (*it)->add_mess(this); 53 } 54 55 56 Message& Message::operator=(const Message& mes) 57 { 58 if(this == &mes) return *this; 59 contents = mes.contents; 60 for(std::set<Folder*>::iterator it = folders.begin(); it != folders.end(); ++it) 61 (*it)->delete_mess(this); 62 63 folders = mes.folders; 64 for(std::set<Folder*>::iterator it = folders.begin(); it != folders.end(); ++it) 65 (*it)->add_mess(this); 66 return *this; 67 } 68 69 Message::~Message() 70 { 71 // 对于每一个folder要删除 每一个 folder 指向自己的信息 72 for(std::set<Folder*>::iterator it = folders.begin(); it != folders.end(); ++it) 73 (*it)->delete_mess(this); 74 std::cout<< contents << std::endl; 75 } 76 77 Folder::~Folder() // 缺少析构函数会导致:如果message删除了,则Folder里面指向垃圾对象,内存报错 78 { 79 // 对于每个message 要删除指向他的folder 80 for(std::set<Message*>::iterator it = messages.begin(); it != messages.end();) 81 { 82 std::set<Message*>::iterator next = it; 83 ++next; 84 (*it)->delete_folder(this); 85 it = next; 86 } 87 std::cout << "~Folder" << std::endl; 88 } 89 90 /*Folder::~Folder() // 这样为啥是错的。 迭代器失效的操作造成。 91 { 92 // 对于每个message 要删除指向他的folder 93 for(std::set<Message*>::iterator it = messages.begin(); it != messages.end(); ++it) 94 { 95 (*it)->delete_folder(this); 96 } 97 std::cout << "~Folder" << std::endl; 98 } 99 */ 100 101 int main() 102 { 103 std::string s1("contents1"); 104 std::string s2("contents2"); 105 106 Message m1(s1); //栈区里面定义对象的先后 107 Message m2(s2); //顺序会影响程序的执行;特别是 108 Folder f1; // Message、Folder的类定义是交叉的。 109 Folder f2; 110 111 m2.add_folder(f2); 112 m1.add_folder(f1); 113 return 0; 114 }