簡體   English   中英

對重載的運算符使用模板時出錯=

[英]Error using template for overloaded operator=

我正在嘗試使用模板為鏈表類編寫重載的賦值運算符,但我一直遇到錯誤。

任何對我做錯事的幫助都會很棒。

我收到的錯誤是“行外定義與LL中的任何聲明都不匹配”。

我的聲明是:

const LL<T>& operator=(const LL<T> &rhsObj);

實現是:

template<typename T>
LL<T>& LL<T>::operator=(const LL<T>& rhsObj) const
{
    if (this!= &rhsObj)
    {
        //no self assignment so OK to continue
        //deallocate left hand side memory
        this->clear();

        count = 0;
        head = NULL;

        cout <<"calling function copyList()" << endl;

        count = 0;
        head = NULL;

        string diCode = "";
        int onNode = 0;

        if(rhsObj.head == NULL)
        {
            cout <<"other list is empty, nothing to do" << endl;

        }
        else
        {
            onNode =0;
            Node<T> *otherCurrent = rhsObj.head;
            while( otherCurrent != NULL)
            {
                int duplicateInfo;
                duplicateInfo = otherCurrent->info;

                push_back(duplicateInfo);

                otherCurrent = otherCurrent ->next;
                onNode++;

            } //END while(otherCurrent != NULL)

        } // END else block of if (otherLL.head == NULL)

    } // END if (this != &rhsObj)

    return *this;
}

在更新的代碼中,錯誤是因為您的聲明是:

const LL<T>& operator=(const LL<T> &rhsObj);

但是嘗試的實現是:

LL<T>& LL<T>::operator=(const LL<T>& rhsObj) const

const的位置實際上很重要。 第一個表示該函數返回一個引用,該引用為const; 第二個意味着您不能在函數中修改*this

尾隨const是函數簽名的一部分,因此編譯器不認為您的實現與最初聲明的函數相對應。 因此,似乎您正在嘗試添加類定義中未聲明的新函數,這是不允許的。

要解決此問題,請使實現與聲明匹配(將const移動)。

暫無
暫無

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

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