簡體   English   中英

重載==函數

[英]Overloading the == function

我目前正在為==運算符創建一個重載函數。 我正在為我的鏈表創建一個hpp文件,我似乎無法讓這個操作符在hpp文件中工作。

我目前有這個:

template <typename T_>
class sq_list 
{

bool operator == ( sq_list & lhs, sq_list & rhs) 
{
    return *lhs == *rhs;
};

reference operator * ()     {
        return _c;
    };

};
}

我得到大約10個錯誤,但它們幾乎重復為錯誤:

C2804:二進制'運算符=='參數太多
C2333:'sq_list :: operator ==':函數聲明中的錯誤; 跳過功能體
C2143:語法錯誤:缺少';' 在'*'之前
C4430:缺少類型說明符 - 假定為int。 注意:C ++不支持default-int

我已經嘗試過改變一些事情,但我一直得到與上面相同的錯誤

任何提示或幫助都非常感謝。

成員運算符只有一個參數,這是另一個對象。 第一個對象是實例本身:

template <typename T_>
class sq_list 
{
    bool operator == (sq_list & rhs) const // don't forget "const"!!
    {
        return *this == *rhs;  // doesn't actually work!
    }
};

這個定義實際上沒有意義,因為它只是遞歸地調用自身。 相反,它應該調用一些成員操作,比如return this->impl == rhs.impl;

您將==重載聲明為類定義的一部分,因為方法實例將獲得。 因此,您請求的第一個參數lhs已經是隱含的:請記住,在實例的方法中,您可以訪問this

class myClass {
    bool operator== (myClass& other) {
        // Returns whether this equals other
    }
}

作為類的一部分的operator ==()方法應該被理解為“這個對象知道如何將自己與其他人進行比較”。

您可以在類外部重載operator ==()以接收兩個參數,兩個對象都要進行比較,如果這對您更有意義。 見這里: http//www.learncpp.com/cpp-tutorial/94-overloading-the-comparison-operators/

http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html

比較運算符非常簡單。 首先使用如下函數簽名定義==:

  bool MyClass::operator==(const MyClass &other) const {
    ...  // Compare the values, and return a bool result.
  }

如何比較MyClass對象是你自己的。

暫無
暫無

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

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