I want to use the -
operator between 3 objects but I can't.
Error:'A A::operator-(A, A)' must take either zero or one argument
I do not know what to do.
class A
{
private:
float x,y;
public:
void set(int a,int b){
x=a;
y=b;
}
void show(){
cout<<"x = "<<x<<" y = "<<y<<endl;
}
A() {}
A operator -(A &obj1){
A temp;
temp.x= x - obj1.x;
temp.y= y - obj1.y;
return temp;
}
};
A A::operator -(A obj1, A obj2);
int main() {
A ob1,ob2,ob,result;
ob1.set(5,7);
ob2.set(10,7);
ob.set(4,9);
result = ob - ob2 -ob1;
ob.show();
return 0;
}
CodePudding user response:
The expression ob - ob2 - ob1
will be treated as ob.operator-(ob2.operator-(ob1))
.
The result of ob2.operator-(ob1)
will be a temporary value (because it's not stored in a variable). And non-constant references can't be bound to temporary values.
Simple solution: Use constant references instead:
// Note const keyword here
// vvvvv
A operator -(A const& obj1)
Also (as noted by Paolo), you have a declaration of an operator-
function which should not be there.
Remove the declaration
A A::operator -(A obj1, A obj2);
CodePudding user response:
There are 2 ways to overload an operator for a class:
class Foo {
public:
Foo operator -(const Foo &rhs) const { ... }
Foo operator (const Foo &rhs) const;
};
Foo Foo::operator (const Foo &rhs) const {
...
}
or
class Foo { ... };
Foo operator -(const Foo &lhs, const Foo &rhs) { ... }
The first is overloading the operator inside the class as a function of the class. It has this
as the left hand side of the operator so you can only specify the right hand side as argument.
The second overloads the general operator outside of the class. It has 2 arguments, the left hand side and the right hand side. It is not a member of the class and won't have access to the private parts, unless you friend it.
You kind of mixed the two styles together and that is what the error is trying to tell you.
You do not need to implement anything to make a - b - c
work as the compiler will transform that into temp = a - b; temp - c;
.