【问题标题】:passing ‘function as ‘this’ argument of ’function' discards qualifiers [-fpermissive]将“function”作为“function”的“this”参数传递会丢弃限定符[-fpermissive]
【发布时间】: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-&gt;next 上的迭代器。
  • @BenjaminNordin 不,您需要建立一个新列表,该列表是其他列表的副本。

标签: c++ linked-list stack


【解决方案1】:

,但如果可能的话,可以通过将“其他”保持为 const 来向我解释如何做到这一点。

不用other.pop(),直接使用other的成员变量即可。

template <typename DataType>
StackLinked<DataType>::StackLinked(const StackLinked<DataType> & other)
{   
    StackLinked<DataType> temp = StackLinked<DataType>();
    StackNode<DataType>* node = other.top;
    while ( node != nullptr )
    {
        temp.push(node->data); // I am guessing data is a member variable of StackNode.
                               // If not, use the right member variable.
        node = node->next;
    }

    node = temp.top;
    while ( node != nullptr )
    {
        push(node->data);
        node = node->next;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多