class CList { public: struct list { char info[100]; struct list *next; }; struct list *head; CList(); CList(const CList &obj); ~CList(); }; Actually, how to make a copy constructor?
class CList { public: struct list { char info[100]; struct list *next; }; struct list *head; CList(); CList(const CList &obj); ~CList(); }; Actually, how to make a copy constructor?
It depends on what you want to receive. You can simply copy the head pointer - in this case it will be an object pointing to the same list.
But if you want to completely copy the entire list - then you have to recursively go through the chain, i.e. create a copy of the list pointed to by head, set the head pointing to it, go to this list (eq you unsuccessfully called it! node would be much better). In it, if the original next not zero - repeat the same steps ...
Like that. In fact, this is the difference between shallow and deep copying ...
Update I would do something like this - the list constructor:
struct list { char info[100]; struct list *next; list(const list& l) { memcpy(info,l.info,100); if (l.next == 0) next = 0; else next = new list(*l.next); } }; and then the CList constructor would
CList(const CList &obj) { if (obj.head == 0) head = 0; else head = new list(*obj.head); } Not compiled, just outlined the idea.
Something like this:
// Harry подсказал, что это явно похоже на список head = new list(); list* current = head; list* forCopy = obj.head; while(forCopy != NULL) { current = new list(); memcpy(current, forCopy, sizeof(list)); forCopy = forCopy.next; current.next = new list(); current = current.next; } Source: https://ru.stackoverflow.com/questions/505298/
All Articles