#include <iostream> #include<vector> #include<string> using namespace std; class AbstractFile{ protected: string name; public: AbstractFile(string n){ name=n; } virtual void Display()=0; // 纯虚函数 }; class File:public AbstractFile{ public: File(string n):AbstractFile(n){} void Display(){ cout<<name<<endl; } }; class Folder:public AbstractFile{ private: vector<AbstractFile *> objvec; //迭代器 public: Folder(string n):AbstractFile(n){} void add(AbstractFile *t){ objvec.push_back(t); } void Display(){ vector<AbstractFile *>::iterator ivec; cout<<name<<endl; for(ivec=objvec.begin();ivec<objvec.end();ivec++) (*ivec)->Display(); } }; int main(int argc, char** argv) { Folder *root=new Folder("C:\\"); File *pa=new File("a.txt"); File *pb=new File("b.txt"); Folder *paa=new Folder("aa"); File *p1=new File("1.cpp"); File *p2=new File("2.cpp"); root->add(pa); root->add(pb); root->add(paa); paa->add(p1); paa->add(p2); root->Display(); //调用Display() delete root; delete pa ; delete pb ; delete p1; delete p2; delete paa; return 0; }
时间: 2024-10-12 22:18:28