object = -object 不编译,尽管运算符重载
object = -object doesn't compile although operators are overloaded
可能的重复项:
如何在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-() {...}
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板