Search code examples
c++operator-keyword

operator== in C++ struct


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.


Solution

  • 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.