簡體   English   中英

Qt運算符!=重載

[英]Qt operator != overloading

I tried to overload the operator !=

    struct Antichoc 
    { 
        quint8 Chariot; 
        quint8 Frittage;

    bool operator!=(const Antichoc &a, const Antichoc &b) 
    { 
        return a.Chariot != b.Chariot || a.Frittage != b.Frittage; 
    }
    }

我得到錯誤:

bool Antichoc :: operator!=(const Antichoc&,const Antichoc&)必須只接受一個參數

為什么這個錯誤

非靜態成員函數采用隱式,隱藏的第一個參數,並帶有指向相同類型的指針。 因此,您的成員運算符實際上有三個參數,應該有兩個。

您可以將其設為非成員運算符:

struct Antichoc { .... };

bool operator!=(const Antichoc &a, const Antichoc &b) 
{ 
    return a.Chariot != b.Chariot || a.Frittage != b.Frittage; 
}

或者使它成為僅接受一個參數的成員。

struct Antichoc 
{ 
    quint8 Chariot; 
    quint8 Frittage;

  bool operator!=(const Antichoc& rhs) const 
  { 
    return Chariot != rhs.Chariot || Frittage != rhs.Frittage; 
  }
};

第一個版本將允許隱式轉換為Antichoc ,在此特定示例中沒有必要。

通常,按照==來實現!=是一個好習慣。

請注意,在C ++ 11中,您可以使用std::tie簡化所有這些邏輯運算符:

#include <tuple>

bool operator!=(const Antichoc &a, const Antichoc &b) 
{ 
    return std::tie(a.Chariot, a.Frittage) != std::tie(b.Chariot, b.Frittage); 
}

暫無
暫無

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

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