问题
Can you help me to write a copy constructor for this List, note that the Data is stored indirectly.
class List {
private:
struct Node {
Data *data;
Node *next;
};
Node *head;
};
You can assume you have a copy constructor of Data class.
Thank you.
回答1:
Your class definition needs to add the function signature:
List(const List& list);
The parameter is the list you are copying from.
You also need to implement this function.
List::List(const List& list)
{
//Iterate through the list parameter's nodes, and recreate the list
//exactly as it is in the list you passed in.
}
Note that you probably don't want to do this:
List::List(const List& list)
{
head = list.head;
}
because instead of being a copy of the list, it's actually a second reference to the same list.
You can call this function like this:
List thisIsAPremadeList;
List copyOfList(thisIsAPremadeList);
And now copyOfList contains a deep copy of everything that thisIsAPremadeList has.
来源:https://stackoverflow.com/questions/42523112/copy-constructor-for-a-pointer-data-linked-list