我的代码在这里给出了分段错误。我不知道为什么会这样。我收到一条警告:' FilesystemObject'是抽象的但具有非虚拟析构函数。我也尝试将析构函数设为虚拟,但这似乎没有任何帮助。
#include<iostream>
#include<list>
using namespace std;
class FilesystemObject{
public:
virtual void print()=0;
};
class File: public FilesystemObject{
public:
File(const string& filename) : fileName(filename) {}
void print() {
cout<< fileName << endl;
}
private:
string fileName;
};
class Directory: public FilesystemObject {
public:
Directory(const string& path) : dirPath(path) {}
~Directory() {
for_each(children_.begin(),children_.end(), FilesystemObjectDeallocator());
}
void print() {
cout<<"Printing Directory Filenames"<<dirPath<<endl;
for(list<FilesystemObject*>::iterator it = children_.begin(), itend = children_.end(); it!=itend; ++it)
(*it)->print();
}
void add(FilesystemObject* object) {
children_.push_back(object);
}
void remove(FilesystemObject* object) {
list<FilesystemObject*>::iterator found = find(children_.begin(), children_.end(),object);
if(found!=children_.end())
children_.erase(found);
}
private:
list<FilesystemObject*> children_;
string dirPath;
struct FilesystemObjectDeallocator {
void operator()(FilesystemObject*& p) {
delete p;
}
};
};
int main(int argc, char* argv[]) {
File* file1 = new File("test1");
File* file2 = new File("test2");
File* file3 = new File("test3");
Directory* directory1 = new Directory("/root");
Directory* directory2 = new Directory("/username");
directory2->add(file1);
directory2->add(file2);
directory1->add(file3);
directory1->add(directory2);
directory2->add(directory1);
directory1->print();
return 0;
}