实验十
#include <iostream> #include <list> #include <memory> #include <utility> #include <cstddef> using namespace std; class File { public: File(string name) { m_name = name; } virtual ~File() {} virtual void Add(std::unique_ptr<File>) {}//这里默认实现为空函数,leaf节点中不用实现为空了 virtual void Show(int depth) {} // 这里默认实现为空函数,leaf节点中不用实现为空了 protected: string m_name; }; //具体公司 class ConcreteFile : public File { public: ConcreteFile(string name) : File(name) {} virtual ~ConcreteFile() { for (auto& File : m_listFile) { File.reset(nullptr); } } void Add(std::unique_ptr<File> pCom) { m_listFile.push_back(std::move(pCom)); } //位于树的中间,可以增加子树 void Show(int depth) { for (int i = 0; i < depth; i++) cout << "-"; cout << m_name << endl; auto iter = m_listFile.begin(); for (; iter != m_listFile.end(); iter++) //显示下层结点 (*iter)->Show(depth + 2); } private: list<std::unique_ptr<File>> m_listFile; }; //具体的部门,财务部 class FinanceDepartment : public File { public: FinanceDepartment(string name) :File(name) {} virtual ~FinanceDepartment() {} virtual void Show(int depth) //只需显示,无限添加函数,因为已是叶结点 { for (int i = 0; i < depth; i++) cout << "-"; cout << m_name << endl; } }; //具体的部门,人力资源部 class HRDepartment :public File { public: HRDepartment(string name) :File(name) {} virtual ~HRDepartment() {} virtual void Show(int depth) //只需显示,无限添加函数,因为已是叶结点 { for (int i = 0; i < depth; i++) cout << "-"; cout << m_name << endl; } }; int main() { auto root = std::make_unique<ConcreteFile>("文件11"); auto leaf1 = std::make_unique < FinanceDepartment>("文件21"); auto leaf2 = std::make_unique < HRDepartment>("文件22"); root->Add(std::move(leaf1)); root->Add(std::move(leaf2)); //分公司 auto mid1 = std::make_unique < ConcreteFile>("文件31"); auto leaf3 = std::make_unique < FinanceDepartment>("文件41"); auto leaf4 = std::make_unique < HRDepartment>("文件42"); mid1->Add(std::move(leaf3)); mid1->Add(std::move(leaf4)); root->Add(std::move(mid1)); //分公司 auto mid2 = std::make_unique < ConcreteFile>("文件32"); auto leaf5 = std::make_unique < FinanceDepartment>("文件43"); auto leaf6 = std::make_unique < HRDepartment>("文件44"); mid2->Add(std::move(leaf5)); mid2->Add(std::move(leaf6)); root->Add(std::move(mid2)); root->Show(0); return 0; }
实验十一