#include<iostream>
#include<list>
#include<string>
using namespace std;
class IFile
{
public:
virtual void display() = 0;
virtual bool add(IFile*) = 0;
virtual bool remove(IFile*) = 0;
virtual list<IFile*> *getChild() = 0;
};
class Dir :public IFile
{
public:
Dir(string name)
{
m_name = name;
m_list = new list < IFile* > ;
m_list->clear();
}
virtual void display()
{
cout << m_name << endl;
}
virtual bool add(IFile*root)
{
m_list->push_back(root);
return 1;
}
virtual bool remove(IFile*root)
{
m_list->push_back(root);
return 1;
}
virtual list<IFile*> *getChild()
{
return m_list;
}
private:
string m_name;
list<IFile*> *m_list;
};
class File :public IFile
{
public:
File(string name)
{
m_name = name;
}
virtual void display()
{
cout << m_name << endl;
}
virtual bool add(IFile*)
{
return 0;
}
virtual bool remove(IFile*)
{
return 0;
}
virtual list<IFile*> *getChild()
{
return NULL;
}
private:
string m_name;
};
void showTree(IFile*root, int lever)
{
root->display();
int i = 0;
if (root->getChild() != NULL)
{
list<IFile*>*mylist = root->getChild();
for (list<IFile*>::iterator it = mylist->begin(); it != mylist->end(); it++)
{
if ((*it)->getChild() == NULL)
{
for (i = 0; i <=lever; i++)
{
cout << "\t";
}
(*it)->display();
}
else
{
for (i = 0; i <= lever; i++)
{
cout << "\t";
}
showTree(*it, lever+1);
}
}
}
}
void main()
{
IFile *root = NULL;
root = new Dir("C");
Dir *dir1 = new Dir("Dir1");
File *file1 = new File("file1");
root->add(dir1);
root->add(file1);
showTree(root,0);
Dir *dir2 = new Dir("Dir2");
File *file2 = new File("file2");
dir1->add(dir2);
dir1->add(file2);
showTree(root, 0);
}
运行结果: