【问题标题】:C++ error: passing const as 'this' argumentC++ 错误:将 const 作为“this”参数传递
【发布时间】:2014-06-26 13:24:49
【问题描述】:

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

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

错误指向==的实现部分 这是摘录: P.S: 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;
}

【问题讨论】:

    标签: c++ templates linked-list operator-overloading


    【解决方案1】:

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

    此外,Element 都来电

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

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

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

    【讨论】:

    • 非常感谢,已修复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多