Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class CloneNotSupported{};
- class Object
- {
- public:
- virtual ~Object(){}
- virtual Object*clone()const{
- throw CloneNotSupported();
- }
- };
- class List : public Object
- {
- friend class Iterator;
- class ListElement
- {
- public:
- ListElement*next;
- Object*object;
- };
- ListElement*start;
- ListElement*end;
- public:
- List(){start=end=0;}
- ~List(){free();}
- List(const List&other){copy(other);}
- List&operator=(const List&other){
- if(&other!=this){
- free();
- copy(other);
- }
- return *this;
- }
- void pushBack(Object*object)
- {
- ListElement*le=new ListElement();
- le->next=0;
- le->object = object;
- if(end)end->next=le;
- end=le;
- if(!start)start=end;
- }
- void pushFront(Object*object)
- {
- ListElement*le=new ListElement();
- le->object = object;
- le->next=start;
- start=le;
- if(!end)end=start;
- }
- protected:
- void free()
- {
- while(start){
- ListElement*tmp=start;
- start=start->next;
- delete tmp->object;
- delete tmp;
- }
- start=end=0;
- }
- void copy(const List&other)
- {
- start=end=0;
- for(ListElement*i=other.start;i;i=i->next){
- pushBack(i->object->clone());
- }
- }
- };
- class Iterator
- {
- const List&list;
- List::ListElement*current;
- public:
- Iterator(const List&l):list(l),current(l.start){}
- Iterator&operator++(){
- if(current)current=current->next;
- return *this;
- }
- Iterator&operator++(int){
- if(current->next)current=current->next; //?
- return *this;
- }
- operator bool()const{return current!=0;}
- Object*get()const{return current->object;}
- };
- class Int: public Object
- {
- public:
- int value;
- Int(int v=0){value=v;}
- void dump()const{std::cout<<value<<std::endl;}
- // Object*clone()const{return new Int(*this);}
- };
- int main(int argc, char* argv[])
- {
- // stwórz listę, dodaj elementy, wypisz
- List list;
- for(int i=0;i<100;i++){
- list.pushFront(new Int(2*i));
- list.pushBack(new Int(2*i+1));
- }
- for(Iterator i(list);i;i++){
- Int*pi=dynamic_cast<Int*>(i.get());
- if(pi)pi->dump();
- }
- // utwórz kopię listy i wypisz zawartość
- try{
- List list2(list);
- for(Iterator i(list2);i;i++){
- Int*pi=dynamic_cast<Int*>(i.get());
- if(pi)pi->dump();
- }
- }
- catch(CloneNotSupported){
- std::cout<<"Clone not supported"<<std::endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement