0

I'm trying to define an == operator in a structure:

typedef struct _tBScan {
    QString strQuadpackNumbers;
    uint uintBegin, uintEnd;
    bool operator==(const struct _tBScan& a, const struct _tBScan& b) {
        return (a.strQuadpackNumbers.compare(b.strQuadpackNumbers) == 0 &&
                a.uintBegin == b.uintBegin && a.uintEnd == b.uintEnd);
    }
} tBScan;

This won't compile, I get:

C2804: binary 'operator ==' has too many parameters
C2333: '_tBScan::operator ==' error in function: declaration: skipping function body

I'm using Qt 5.9.2 and MSVC 2015, I need to define this so I can use the QList compare function.

SPlatten
  • 5,334
  • 11
  • 57
  • 128
  • Make it a non-member function. Besides the two parameter, member function requires an instance to be called. – songyuanyao Sep 08 '21 at 10:22
  • @songyuanyao, can you explain more, it has to be defined as a method in the structure as the its used in QList – SPlatten Sep 08 '21 at 10:24
  • When defining operator in class, first operand is `this`, i.e. current object. You can move it out of class or keep it as member, remove one of the arguments and use `this` instead. – Yksisarvinen Sep 08 '21 at 10:24
  • or memeber with one argument. `operator==` has the left operand and the right operand, yours has 3 in total, which isnt right. `tbScan.operator==( a,b)` when you want `tbScan.operator==(a);` – 463035818_is_not_an_ai Sep 08 '21 at 10:24
  • 1
    @SPlatten It doesn't have to be a member, unless `QList` uses `x.operator==(y)` instead of `x == y` for some unholy reason. – Yksisarvinen Sep 08 '21 at 10:25
  • @Yksisarvinen, the QList compare function requires an overload == operator. – SPlatten Sep 08 '21 at 10:27
  • 1
    @SPlatten But it doesn't require it to be a member function. This compendium might be worth to read: https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading/4421715#4421715 – Yksisarvinen Sep 08 '21 at 10:28
  • 2
    No need for `typedef struct ss {} sss` in C++. –  Sep 08 '21 at 10:37

1 Answers1

1

When overloading an binary operator as a member function, the first parameter is this pointer. In the signature you have defined the operator==, it will take 3 arguments. However, it can only take two.

In you case I would recommend making it a non-member function.

typedef struct _tBScan {
    QString strQuadpackNumbers;
    uint uintBegin, uintEnd;
} tBScan;

bool operator==(const struct _tBScan& a, const struct _tBScan& b) {
        return (a.strQuadpackNumbers.compare(b.strQuadpackNumbers) == 0 &&
                a.uintBegin == b.uintBegin && a.uintEnd == b.uintEnd);
}

When you overload the, let's say, operator@ the expression _tBScan @ _smt is resolved into.

_tBScan.operator@(_smt);

When it's not a member function the expression is resolved into

operator@(_tBScan, _smt);

So the compiler searches the overload of either of them.

Karen Baghdasaryan
  • 2,407
  • 6
  • 24