在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){
^
...
我该如何解决这个问题?
Vector Vector::operator-(const Vector&)const;
和Vector Vector::operator-() const;
。 - Andrew