【发布时间】:2018-10-02 19:05:57
【问题描述】:
我的堆栈 ADT 使用链表的复制构造函数之一似乎主要工作,除了它导致的一个错误。它显然与“其他” StackLinked 作为 const 类型有关,并且 pop() 函数正在改变它,但可以向我解释我如何通过保持“其他”仍然是 const 来做到这一点。如果没有,我还能怎么做。
这里是复制构造函数:
template <typename DataType>
StackLinked<DataType>::StackLinked(const StackLinked<DataType> & other)
{
int tempSize = other.getSize();
StackLinked<DataType> temp = StackLinked<DataType>();
for(int i = 0; i < tempSize; i++)
{
temp.push(other.pop()); //error is on this line on the pop function
}
for(int i = 0; i < tempSize; i++)
{
push(temp.pop());
}
}
这里是 pop() 和 push() 函数:
template <typename DataType>
DataType StackLinked<DataType>::pop()
{
StackNode * temp = top->next;
delete top;
top = temp;
size--;
}
template <typename DataType>
void StackLinked<DataType>::push(const DataType & newDataItem)
{
StackNode * temp = top;
top = new StackNode(newDataItem, temp);
size++;
}
而主函数只是简单地创建了一个新的 StackLinked 对象:
#include "StackLinked.h"
#include "StackLinked.cpp"
#include <iostream>
using namespace std;
int main(void)
{
StackLinked<int> test = StackLinked<int>();
}
最后报错:
StackLinked.cpp:21:9: error: passing ‘const StackLinked<int>’ as ‘this’ argument of ‘DataType StackLinked<DataType>::pop() [with DataType = int]’ discards qualifiers [-fpermissive]
temp.push(other.pop());
【问题讨论】:
-
查看
other的类型。它有什么告诉你它不能被修改吗? -
所以我应该删除 const 吗?
-
@BenjaminNordin 不,然后复制堆栈会清空它。您将不得不依赖实现细节,可能是
top->next上的迭代器。 -
@BenjaminNordin 不,您需要建立一个新列表,该列表是其他列表的副本。
标签: c++ linked-list stack