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

C++ error: passing const as 'this' argument

本文关键字:参数传递 this 错误 const C++      更新时间:2023-10-16

这是一个链表,我试图过载==,它给了我错误:错误:传递'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;
}

这是我剩下的可能相关的代码。我没有发布我所有的代码,因为一切都很好,包括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;
}

.

.//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;
}

声明为const的方法只能调用其他const方法。它们不能是非const方法。在您的案例方法中,operator ==被声明为const。从operator ==内部,您正在尝试调用方法Element,这是非const。这是你的错误。

而且,两个Element调用

if (eq.Element(i) != Element(i))

无效。第一个调用是无效的,因为eqconst引用,这意味着您不能通过它调用任何非const方法。由于上述原因,第二个调用无效。

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