首页 > 解决方案 > 将 'function 作为 'function' 的 'this' 参数传递会丢弃限定符 [-fpermissive]

问题描述

我使用链表的堆栈 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++;
    }

而 main 函数只是简单地创建了一个新的 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());

标签: c++linked-liststack

解决方案


,但如果可能的话,可以通过将“其他”保持为 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;
    }
}

推荐阅读