我需要做一个深度复制,我是否正确使用了我的复制构造函数?

I need to do a deep copy, am I using my copy constructor correctly?

本文关键字:复制 构造函数 我的 是否 深度 一个      更新时间:2023-10-16

我需要做一个深度复制。 我是否正确使用了复制构造函数?我应该更改什么?

#include <iostream>
#include <sstream>
using namespace std;
class LinkedList
{
public:
int data;
LinkedList* prevNode;
LinkedList()
{
int dd = 0;
prevNode = nullptr;
}
LinkedList(int dd, LinkedList* pr)
{
data = dd;
prevNode = pr;
}
};
class Stack
{
private:
LinkedList* topNode;
public:
Stack();
Stack(const Stack& original);
~Stack();
bool isEmpty() const;
int top() const;
int pop();
void push(int);
};
Stack::Stack()
{
topNode = nullptr;
}
Stack::Stack(const Stack& original)
{
this->topNode = original.topNode;
}
Stack::~Stack()
{
while (!isEmpty())
{
pop();
}
}
bool Stack::isEmpty() const
{
if (topNode == NULL)
{
return true;
}
return false;
}
int Stack::top() const
{
if (isEmpty())
{
throw runtime_error("error: stack is empty");
}
return topNode->data;
}
int Stack::pop()
{
int topVal = top();
LinkedList* oldtop = topNode;
topNode = topNode->prevNode;
return topVal;
}
void Stack::push(int newData)
{
LinkedList* newNode = new LinkedList(newData, topNode);
topNode = newNode;
}
int returnNumber(string inputString)
{
istringstream fr(inputString); 
int number;
while (fr >> number)
{ 
return number;
}
if (fr.fail())
{
throw runtime_error("error: not a number");
}
return number;
}
void list(Stack s)
{
cout << "[";
while (!s.isEmpty())
{
cout << s.pop();
if (!s.isEmpty())
{
cout << ",";
}
}
cout << "]" << endl;
}
void readCommands(Stack& newStack)
{
string command = " ";
while (command != "end")
{
cout << "stack> ";
cin >> command;
cout << endl;
if (cin.eof())
{
break;
}
try 
{
if (command == "top")
{
cout << newStack.top() << endl;
}
else if (command == "pop")
{
cout << newStack.pop() << endl;
}
else if (command == "push")
{
string inputValue;
cin >> inputValue;
int number = returnNumber(inputValue);
newStack.push(number);
cin.ignore();
}
else if (command == "list")
{
list(newStack);
}
else
{  
if (command != "end")
{
throw runtime_error("error: invalid command");
}
}
}
catch (runtime_error e)
{
cout << e.what() << endl;
} 
}
}
int main()
{
Stack newStack;
readCommands(newStack);
return 0;
}

我需要做一个深度复制,我是否正确使用了我的复制构造函数?

不。要执行深层复制,您需要在新堆栈中分配新空间。这将看起来像这样:

class LinkedList
{
public:
static LinkedList* Copy(LinkedList* c) {
if(c == nullptr) {
return nullptr;
} else {
return new LinkedList(data, Copy(prevNode));
}
}
};

此静态函数接受任何指针并创建其值和列表的副本。

然后,在您的堆栈中:

Stack::Stack(const Stack& original)
{
this->topNode = LinkedList::Copy(original.topNode);
}

通过这样做,您实际上是在创建新的内存,而不是盲目复制指针。这就是深度复制的伟大思想。

如果你仍然对深度副本的工作原理感到困惑,我建议你咨询你的教科书或教授。