So, I have the following class:
typedef double decimal;
class Ratio {
int num, den;
decimal val;
public:
Ratio() { num = 1, den = 1, val = (decimal)num / den; }
Ratio update(int a, int b) {
num *= a, den *= b;
val = (decimal)num / den;
return *this;
}
decimal v(void) { return val; }
friend ostream &operator<<(ostream &out, const Ratio &R) {
return (out << R.num << ':' << R.den);
}
};
When I use the member functions in the output stream as:
cout<<"R = "<<R.update(2,1)<<"\tvalue = "<<R.v();
where R is of type Ratio, the function to the right end is called first so it displays the updated ratio but the non-updated value:
R = 2:1 value = 1
I overcame this by splitting the stream in two:
cout<<"R = "<<R.update(2,1), cout<<"\tvalue = "<<R.v();
so that I "force" .update() to be called first. Is there another way to achieve this, using only one stream for output?