Operator overloading with different object types as operands in C++

前端 未结 1 405
眼角桃花
眼角桃花 2021-01-28 07:30
class myClass
{
public:
    int myVal;
    myClass(int val) : myVal(val)
    {

    }
    myClass& operator+(myClass& obj)
    {
        myVal = myVal + obj.myVa         


        
相关标签:
1条回答
  • 2021-01-28 08:00

    You typically implement the binary arithmetic += (compound-assignment) operator as a member function, and + as a non-member function which makes use of the former; this allows providing multiple overloads of the latter e.g. as in your case when the two operands to the custom binary arithmetic operators are not of the same type:

    class MyClass
    {
    public:
        int myVal;
        MyClass(int val) : myVal(val) {}
        
        MyClass& operator+=(int rhs) {
            myVal += rhs;
            return *this;
        }
    };
    
    inline MyClass operator+(MyClass lhs, int rhs) {
        lhs += rhs;
        return lhs;
    }
    
    inline MyClass operator+(int lhs, MyClass rhs) {
        rhs += lhs;
        return rhs;
        // OR:
        // return rhs + lhs;
    }
    
    int main() {
        MyClass obj1(10);
        MyClass obj2(10);
        obj1 = 20 + obj2;
        obj1 = obj1 + 42;
    }
    

    For general best-practice advice on operator overloading, refer to the following Q&A:

    • What are the basic rules and idioms for operator overloading?
    0 讨论(0)
提交回复
热议问题