I was wondering if it is possible to have overload the C++ >> operator in this way
Account& operator>> (double left, Account &right)
{
right.deposit(left);
return right;
}
Account& operator>> (Account &left, double right)
{
left.withdraw(right);
return left;
}
I was wondering if the >> operator had this functionality
so I could do something like this
account1 >> 200 >> account2
Which would withdraw 200 from the first account and then deposit it into the second account.
>Solution :
As described, this is not going to work for the following simple reason:
account1 >> 200 ...
When this gets evaluated this ends up calling the following overload:
Account& operator>> (Account &left, double right)
Your attention is drawn to the fact that this overload returns an Account &. That’s declared right there, in black and white. Let’s keep going:
... >> account2
And now, the left-hand side of this operator>> is now an Account &, what the overload returned. It is not a double anymore. And it needs to be a double in order for the other overload to pick up the slack, and bring it home. That’s how overloaded operators work in C++.
The simplest solution is probably to simply return a double value from the first overload:
double operator>> (Account &left, double right)
{
left.withdraw(right);
return right;
}
Now the result of this expression is a double value, which will have a much easier time getting the other overloaded operator>> to come into picture.