There are some classes, functions and techniques that are not required in the solution of this assignment, but which you will find very useful in writing up your solution. In this document, we present some of the C++ features that you should consider using.
// Return the smaller of the receiver and the argument.
Fraction Fraction::min( Fraction other ) {
if( other is less than the receiver ) {
return other;
} else {
// How do you return the receiver???
}
}
It turns out that there's some syntax to let you refer to the receiver:
(*this)
. Don't worry about what this means for now. Just
remember that it can refer to the receiver of a method call:
Fraction Fraction::min( Fraction other ) {
if( other is less than the receiver ) {
return other;
} else {
return (*this);
}
}
Fraction
class. Here's one sensible way
to do that:
Fraction Fraction::operator +( Fraction other ) {
int numerator_of_return = /* something here */
int denominator_of_return = /* something here */
Fraction result( numerator_of_return, denominator_of_return );
return result;
}
What's important here is the idea of constructing a new instance
as a local variable and then returning it.
There's actually an even nicer way to do this. It involves a subject
I made an effort to avoid in the past: calling the constructor directly.
This is an idea that "didn't make sense" in the Screen
class,
but which applies here.
Fraction Fraction::operator +( Fraction other ) {
int numerator_of_return = /* something here */
int denominator_of_return = /* something here */
return Fraction( numerator_of_return, denominator_of_return );
}
This version of the function constructs a temporary Fraction
instance and immediately returns it.
INT_MAX, INT_MIN
limits.h
,
and they're called INT_MAX
and INT_MIN
. Note
that the following code is incorrect:
if( a + b > INT_MAX ) {
cout << "Overflow!" << endl;
}
You'll have to be a little more clever than that.
ostrstream
ostrstream
. It's just another kind
of output stream. But this one sends its output to a character buffer.
Useful for writing text to a string instead of directly to the screen.
Here's an example:
#include <strstrea.h> // use strstream.h on non-NT systems
void frobnicate( int n )
{
char buf[ 100 ];
ostrstream oss( buf, 100 );
oss << "You gave me " << n;
// buf now contains the string "You gave me " followed by
// the textual representation of n.
cout << buf << endl;
}