重载运算符 + 并执行 a + b 其中 a 是 int 和 b 自定义对象

Overloading operator + and doing a + b where a is int and b custom object

当第二个参数是 int 时,我为我的自定义 class 重载了 + 运算符。例如,如果我的对象是 x,那么 x + 7 是可能的,而 7 + x 则不是。我怎样才能使后者成为可能?

我认为在这里没有必要包含我的 class 代码。

Overloading operator + and doing a + b where a is int and b custom object

通过定义重载operator+(int a, custom b).

然而,使自定义类型可从 int 隐式构造可能更可取,在这种情况下,您只需要一个运算符重载 operator+(custom a, custom b),它可以与 custom 和 [=13 的所有组合一起使用=].