【发布时间】:2019-10-17 21:20:05
【问题描述】:
我需要做一个深拷贝。我是否正确使用了我的复制构造函数?我应该改变什么?
#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;
}
【问题讨论】:
-
看起来是在做浅拷贝。你应该做一个深拷贝。
-
这与编译器生成的默认复制构造函数完全相同。
-
当你完成这项工作时,将其用于代码审查codereview.stackexchange.com(不过需要先工作)。
-
对于
new的每次调用必须对应到delete的调用。我没有看到任何删除调用(也许当您弹出一个项目并且不保留参考时?)。 -
请不要这样删除你的问题!这使得奇普斯特的回答一文不值。我已将其回滚到以前的编辑。您可以不说谢谢,而是对答案投赞成票并接受(通过单击答案左侧的大勾号)。
标签: c++ linked-list stack copy-constructor