如何重载 object = constant int + object

How to overload object = constant int + object

#include<iostream>
using namespace std;

class mango
{
public:
    int qnt;
    mango(int x = 0)
    {
        qnt = x;
    }
    mango operator+(const int a)
    {
        mango temp;
        temp.qnt = a + this->qnt;
        return temp;
    }
};

int main()
{
    mango obj(5);
    obj = obj + 5;
    cout<<obj.qnt<<endl; // shows 10;
    return 0;
}

现在要重载object = constant_int + object,即

obj = 5 + obj;

我想在左侧保留常量整数并将总和存储在对象中。怎么做?

很简单,在class

中定义重载
class mango
{
    ...
};

mango operator+(const int a, const mango& b)
{
    ...
}

实际上一般认为所有的对称和反对称算子都应该在class中定义。所以你的 mango + int 也应该移出 class.

mango operator+(const mango& a, const int b)
{
    ...
}