artoon
artoon

Reputation: 739

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

I get the error :

bool Antichoc::operator!=(const Antichoc&, const Antichoc&) must take exactly one argument

Why this error

Upvotes: 1

Views: 5874

Answers (1)

juanchopanza
juanchopanza

Reputation: 227418

Non-static member functions take an implicit, hidden first parameter with a pointer to the same type. So your member operator actually has three parameters, where it should have two.

You could either make it a non-member operator:

struct Antichoc { .... };

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

Or make it a member taking only one argument.

struct Antichoc 
{ 
    quint8 Chariot; 
    quint8 Frittage;

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

The first version would allow for implicit conversions to Antichoc, which is not necessary in this particular example.

Usually it is good practice to implement != in terms of ==.

Note that in C++11 you can simplify all of these logical operators by using 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); 
}

Upvotes: 7

Related Questions