lundi 30 novembre 2020

How to use binary operator oveloading correctly [duplicate]

How should binary operator be overloaded,
CMyClass operator-(const CMyClass& oMyClass) const or
CMyClass operator-(const CMyClass& oMyClass)
What is the difference between both, Can the first call replace the second one completely.
I have found that using the second one only I wont be able to add const MyClass as LHS.

#include <iostream>
class CMyClass
{
    int m_y{ 0 };
    int m_x{ 0 };

public:
    CMyClass()
    {
    }

    CMyClass(int x, int y) :
        m_x{ x }, m_y{ y }
    {}

    CMyClass operator-(const CMyClass& oMyClass) const
    {
        CMyClass oReturn;
        oReturn.m_x = m_x - oMyClass.m_x;
        oReturn.m_y = m_y - oMyClass.m_y;
        return oReturn;
    }

    CMyClass operator-(const CMyClass& oMyClass)
    {
        CMyClass oReturn;
        oReturn.m_x = m_x - oMyClass.m_x;
        oReturn.m_y = m_y - oMyClass.m_y;
        return oReturn;
    }
};

int main()
{
    const CMyClass p1(10, 10);
    const CMyClass p2(5, 5);

    CMyClass p3 = p1 - p2;
    // ...
}

Aucun commentaire:

Enregistrer un commentaire