C++错误:将const作为'this'参数传递

Seb*_*Seb 1 c++ templates linked-list operator-overloading

这是一个链表,我正在尝试重载==,它给了我错误:错误:将'const Linked_List传递为'ItemType Linked_List :: Element(int)[with ItemType = int]'的'this'参数丢弃限定符.

我必须检查两个链表是否具有相同数量的元素,以及每个元素是否成对相等.

错误指向==的实现部分这里是摘录:PS:element(i)返回链表的i位置的值

template <typename ItemType>
bool Linked_List <ItemType>::operator == (const Linked_List &eq)const {
    if (eq.Items != Items){
        return false;
    }
    if (eq.Items == 0){
        return true;
    }
    for (int i = 0; i < eq.Items; i++){
        if (eq.Element(i) != Element(i)){     //error points here
            return false;
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

这是我可能相关的其余代码.我没有发布我的所有代码,因为一切正常,包括element(),只有重载不起作用.

//.h
template <typename ItemType>
class Node
{
    public:
        ItemType Data;
        Node <ItemType> *next;
};

template <typename ItemType>
class Linked_List
{
    public:   
        Node <ItemType> *start;
        int Items;
        Linked_List();
        ItemType Element(int num);
        bool operator == (const Linked_List &eq)const;
}
Run Code Online (Sandbox Code Playgroud)

.

.//cpp
#include "Linked_List.h"
template <typename ItemType>
Linked_List <ItemType>::Linked_List(){
    start = NULL;
    Items = 0;
}
template <typename ItemType>
ItemType Linked_List <ItemType>::Element(int num){
    ItemType result = 0;
    if (start == NULL){
        return result;
    }
    Node <ItemType> *nnode;
    nnode = start;
    int current_position = 0;
    while (current_position < num){
        current_position++;
        nnode = nnode -> next;
    }

    result = nnode -> Data;
    nnode = NULL;
    delete nnode;
    return result;
}
template <typename ItemType>
bool Linked_List <ItemType>::operator == (const Linked_List &eq)const {
    if (eq.Items != Items){
        return false;
    }
    if (eq.Items == 0){
        return true;
    }
    for (int i = 0; i < eq.Items; i++){
        if (eq.Element(i) != Element(i)){      //error
            return false;
        }
    }
    return true;
}

int main(){
    Linked_List <int> test8;
    Linked_List <int> test7;
    cout << (test8 == test7) << endl;
}
Run Code Online (Sandbox Code Playgroud)

AnT*_*AnT 5

声明为的const方法只能调用其他const方法.它们不能是非const方法.在你的情况下,方法operator ==被声明为const.从operator ==你内部试图调用方法Element,这是非const.这是你的错误.

而且,两个Element电话都在

if (eq.Element(i) != Element(i))
Run Code Online (Sandbox Code Playgroud)

无效.第一个调用是无效的,因为它eq是一个const引用,这意味着你不能通过它调用任何非const方法.由于上述原因,第二次呼叫无效.

要么声明你的Element方法,const要么提供第二个const版本,Element以及非const 版本.我看到你的元素按值返回结果,这意味着你可以简单地将其声明为const.