链表运算符重载问题

时间:2014-02-27 12:25:50

标签: c++ operator-overloading operator-keyword

我试图构建自己的链表类并且遇到= operator overloading.的问题据我所知,我们应该在重载赋值运算符时使用const参数,比如使用linked_list<T>& operator=( const linked_list<T>& a)。然而,编译器给了我错误,除非我把linked_list<T>&改为。编者会停下来 if(this->head==a.front()),给我错误

11  error C2662: 'linked_list<T>::front' : cannot convert 'this' pointer from 'const linked_list<T>' to 'linked_list<T> &'

以下是详细信息。

#ifndef _LINKED_LIST_H_
#define _LINKED_LIST_H_
template <class T>
struct node
{
    T data;
    node<T>* next;
};
template <class T>
class linked_list
{
   private:
    node<T>* head;
   public:
    linked_list<T>();
    linked_list<T>(const linked_list<T>& a);
    ~linked_list<T>();
    linked_list<T>& operator=(const linked_list<T>& a);
    bool isEmpty();
    int size() const;
    void insert_front(T a);
    void insert_end(T a);
    void erase_end();
    void erase_front();
    void print() const;
    void erase(node<T>* a);
    node<T>*& front()
    {
        node<T>* ptr = new node<T>;
        ptr = head;
        return ptr;
    }
    void setFront(node<T>* a);
};
#endif
template <class T>
linked_list<T>& linked_list<T>::operator=(const linked_list<T>& a)
{
    if (this->head == a.front())  // the error mentioned happened here. however,
                                  // if no const in the parameter, it would be
                                  // no error
    {
        return *this;
    }
    while (head != nullptr) erase_front();
    node<T>* copy;
    copy = a.front();
    while (copy->next != nullptr)
    {
        insert_end(copy->data);
        copy = copy->next;
    }
    return *this;
}

任何人都可以提供帮助吗?感谢。

2 个答案:

答案 0 :(得分:1)

当访问器返回对所拥有结构的引用时,通常最好实现两个版本:一个是非const并返回一个非const引用,另一个是const并返回一个const引用。这样它就可以用于变异和非变异的上下文中。 front()将是一个很好的候选人。

虽然是旁注 - 您可能不希望在公共node接口中公开linked_list,特别是非const引用它们。这就是完全封装在课堂上的那种东西。

答案 1 :(得分:1)

问题是front()不是const成员函数,而你试图在const实例上调用它。