简体   繁体   中英

linked list operator overloading issue

i tried to build up my own linked list class and got a problem with the = operator overloading. as far as i know, we should use const parameter when overloading the assignment operator, say using linked_list<T>& operator=( const linked_list<T>& a) . however, the complier gave me errors unless i put linked_list<T>& a instead. the complier would stop at if(this->head==a.front()) , giving me Error

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

below are the details.

#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;
}

anybody can help? thanks.

When an accessor returns a reference to an owned structure, it's usually a good idea to implement two versions: One which is non-const and returns a non-const reference, and one which is const and returns a const reference. That way it can be used in both mutating and non-mutating contexts. front() would be a good candidate for this.

Though a side note -- you probably don't want to expose your node s in the public linked_list interface, particularly non-const references to them. That's the sort of thing to encapsulate entirely in the class.

问题在于front()不是const成员函数,并且您试图在const实例上调用它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM