簡體   English   中英

鏈表運算符重載問題

[英]linked list operator overloading issue

我試圖建立自己的鏈表類,並且= operator overloading.遇到問題= operator overloading. 據我所知,我們應該在重載賦值運算符時使用const參數,比如使用linked_list<T>& operator=( const linked_list<T>& a) 但是,除非我放了linked_list<T>& a,否則編譯器給了我錯誤。 編譯器將停在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;
}

有人可以幫忙嗎? 謝謝。

當訪問器返回對擁有的結構的引用時,通常最好實現兩個版本:一個版本為非常量,返回一個非常量引用,另一個版本為const,返回一個const引用。 這樣,它可以在變異和非變異上下文中使用。 front()將是一個很好的選擇。

盡管有個旁注-您可能不希望在公共linked_list接口中公開您的node ,尤其是對它們的非常量引用。 那是完全封裝在類中的東西。

問題在於front()不是const成員函數,並且您試圖在const實例上調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM