object = -object 不编译,尽管运算符重载

object = -object doesn't compile although operators are overloaded

本文关键字:运算符 重载 编译 -object object      更新时间:2023-10-16

可能的重复项:
如何在C++中重载一元减号运算符?

我有一个 C 类,它重载了许多运算符:

class C
{
  ...
  C& operator-=(const C& other) {...}
  const C operator-(const C& other) {...}
}
inline const C operator*(const double& lhs, const C& rhs)

现在我想反转 C 类型的对象

c = -c;

gcc给了我以下错误:

no match for >>operator-<< in >>-d<<
candidate is: const C C::operator-(const C&)

使用 c = -1*c 有效,但我希望能够缩短它。我的班级缺少什么?


已解决:添加了一元运算符-:

C operator-() const {...}

作为C的成员。

你重载了二进制 - 运算符。您还需要重载一元运算符

如何在C++重载一元减号运算符?

对于如何重载一元 - 运算符

你重载了二进制-、二进制*和复合赋值-=运算符。表达式c = -c使用一元-,你永远不会重载。

如果你想通过一个独立的(可能是朋友)函数重载一元-,你必须相应地声明它。只需添加一个 friend 关键字即可在类定义中完成

class C
{
  ...
  friend C operator-(const C& other) {...}
};

或者通过将函数声明移到类定义之外

class C
{
  ...
};
inline C operator -(const C& other) {...}

或者,如果要将一元-声明为成员,则必须不带参数声明它

class C
{
  ...
  C operator-() const {...}
};

进行此更改:

const C operator-() {...}