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

时间:2016-05-27 15:16:58

标签: c++ operator-overloading

在C ++中,如何区分一元和二元减号运算符的运算符重载函数?

我试图使用以下代码重载:

Vector Vector::operator-(){
  return Vector(-x,-y,-z);
}

Vector Vector::operator-(const Vector& v){
  return this* + (-v);
}

但这会产生很多错误:

vector.cpp: In member function ‘Vector Vector::operator-(const Vector&)’:
vector.cpp:88:20: error: passing ‘const Vector’ as ‘this’ argument of ‘Vector Vector::operator-()’ discards qualifiers [-fpermissive]
   return this* + (-v);
                    ^
vector.cpp:88:16: error: no match for ‘operator+’ (operand type is ‘Vector’)
   return this* + (-v);
                ^
vector.cpp:88:16: note: candidates are:
vector.cpp:70:8: note: Vector Vector::operator+(const Vector&)
 Vector Vector::operator+(const Vector& v){
        ^
...

如何解决此问题?

1 个答案:

答案 0 :(得分:5)

1. v通过引用传递给const,它不能用非const成员函数调用。由于operator-operator+(一元和二元版本)都不修改类的成员,因此应该将它们作为const成员函数。

Vector Vector::operator-() const {
  return Vector(-x,-y,-z);
}

2.Change

return this* + (-v);

return *this + (-v);