c++ - 将 '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());
解决方案
,但如果可能的话,可以通过将“其他”保持为 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;
}
}
推荐阅读
- sql - 消息 8114,级别 16,状态 5,第 2 行将数据类型 nvarchar 转换为 bigint 时出错
- java - 是否可以将 HERE XYZ 地图插入 Android Studio 项目?
- c# - 来自用户输入字段的唯一字母 c#
- python - 带有python的Sharepoint日历api
- python - 如果它们之间存在匹配,如何从第二个df中获取一个项目
- c++ - 静态成员函数中的返回值类型自动推导失败
- docker - 使用 jnlp-slave 的打包机的 Dockerfile
- swift - 如何运行多个 NSRegularExpression 一次
- java - 查找数字的 sqrt
- c - 如何输入大小未知的字符串