简体   繁体   中英

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

class myClass
{
public:
    int myVal;
    myClass(int val) : myVal(val)
    {

    }
    myClass& operator+(myClass& obj)
    {
        myVal = myVal + obj.myVal;
        return *this;
    }
    myClass& operator+(int inVal)
    {
        myVal = myVal + inVal;
        return *this;
    }
    myClass& operator=(myClass& obj)
    {
        myVal = obj.myVal;
        return *this;
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    myClass obj1(10);
    myClass obj2(10);
    obj1 = obj1 + obj2;
    obj1 = 20 + obj2; // Error : No matching operands for operator "+"
    return 0;
}

How can I implement operator '+' on integer and myClass object types as operands? (obj1 = 20 + obj2)

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 eg 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM