Search code examples
c++operator-overloadingoperator-keywordequals-operator

Code errors at no operator overload


I've got a class using an std::vector> to indicate the item and its count (there can be multiple inventoryitems containing the same item).

I then proceeded to overload the clsInventoryItem its == operator. The setup ends up being: clsInventory.cpp -> including: clsInventory.h clsInventory.h -> including: clsInventoryItem.h clsInventoryItem.h -> including: stdafx.h (which in turns includes the rest of the project, excluding those 2 header files)

The clsInventoryItem contains the following in its header file:

class clsInventoryItem
{
public:
    clsInventoryItem( clsItem* Item, char Quality );
    clsItem* GetItem( );
    char GetQuality( );

    inline bool operator==( const clsInventoryItem& other )
    { /* do actual comparison */
        if (m_Item == other.m_Item
             && m_Quality == other.m_Quality)
        {
            return true;
        }
        return false;
    }
private:
    clsItem* m_Item;
    char m_Quality;
};

And it still gives an error that the equals function isn't overloaded ("Severity Code Description Project File Line Suppression State Error C2678 binary '==': no operator found which takes a left-hand operand of type 'const BrawlerEngineLib::clsInventoryItem' (or there is no acceptable conversion) BrawlerEngineLib d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\utility 290 ")... Anyone knows why this could be the case, and how to potentially solve it?


Solution

  • Your inline bool operator==(const clsInventoryItem& other) is expected to be const.
    To fix that, you need to change inline bool operator==(const clsInventoryItem& other) to inline bool operator==(const clsInventoryItem& other) const.

    Also, you can get rid off the keyword inline, modern compilers will ignore the keyword and older compilers use it as a hint only and decide whether or not to inline the function on their own. They are pretty good at it ;-)