简体   繁体   English

使用不同的 object 类型作为 C++ 中的操作数的运算符重载

[英]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?如何在 integer 和 myClass object 类型上实现运算符“+”作为操作数? (obj1 = 20 + obj2) (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;您通常将二进制算术+= ( 复合赋值) 运算符实现为成员 function,并将+作为非成员 function 实现,后者利用前者; 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:有关运算符重载的一般最佳实践建议,请参阅以下问答:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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