Я пробовал смотреть видео и старые сообщения, но по-прежнему очень сложно понять концепцию конструкторов копирования. Кто-нибудь прояснит это для меня? Мой класс на самом деле не покрывал эту часть на 100%, мой профессор сосредоточился главным образом на конструкторах и деструкторах.Как создать и выполнить конструктор копирования для связанного списка?
Главная CPP
#include <iostream>
#include "Header.h"
using namespace std;
int main()
{
node access;
access.getData();
access.outData();
system("pause");
return 0;
}
Заголовочный файл
#include <iostream>
using namespace std;
class node
{
public:
node(); // Had to create my own default constructor because of my copy constructor.
node(const node &n); // This is a copy constructor.
~node();
void getData();
void outData();
private:
int num;
int lCount = 0; // Counts the number of nodes, increments after each user input.
int *ptr; // Where the linked list will be copied into
node *next;
node *first;
node *temp;
node *point;
};
node::node()
{
num = 0;
}
node::node(const node &n)
{
temp = first;
ptr = new node;
for (int i = 0; i < lCount; i++)
{
ptr[i] = temp->num;
temp = temp->next;
}
}
node::~node() // Deletes the linked list.
{
while (first != NULL)
{
node *delP = first; // Creates a pointer delP pointing to the first node.
first = first->next; // "Removes first node from the list and declares new first.
delete delP; // Deletes the node that was just removed.
}
cout << "List deleted" << endl;
}
void node::getData() // Simple function that creates a linked list with user input.
{
int input = 0;
point = new node;
first = point;
temp = point;
while (input != -1)
{
cout << "Enter any integer, -1 to end." << endl;
cin >> input;
if (input == -1)
{
point->next = NULL;
break;
}
else
{
lCount++;
point->num = input;
temp = new node;
point->next = temp;
point = temp;
}
}
}
void node::outData()
{
temp = first;
cout << "Original" << endl;
while (temp->next != NULL)
{
cout << temp->num << endl;
temp = temp->next;
}
cout << "Copied" << endl;
for (int i = 0; i < lCount; i++)
{
cout << ptr[i] << endl;
}
}
Этот небольшой фрагмент кода является то, что у меня возникли проблемы с, в частности:
node::node(const node &n)
{
temp = first;
ptr = new node;
for (int i = 0; i < lCount; i++)
{
ptr[i] = temp->num;
temp = temp->next;
}
}
https://www.tutorialspoint.com/cplusplus/cpp_copy_constructor.htm –
Возможная дубликат [Создание конструктора копирования для связанного списка] (http://stackoverflow.com/questions/7811893/creating-a-copy-construct или-для-связанного списка) –
@JasonC Я просмотрел это уже, а также предыдущие сообщения. Я просто не понимаю, глядя на чужой код. Я надеюсь, что, имея свой собственный код, чтобы посмотреть, это очистит его для меня. –