Name______________________________________________________________
1. Let us return to the Fraction class. Relevant parts of the Fraction class definition are listed below:
class Fraction {
public:
//you may assume that copy
constructor and operator= are fully implemented
…
private:
int numerator, denominator;
//denominator cannot be zero
};
a) (25%) Implement operator^. operator^ would be used by a client as follows:
Fraction f(2,3); //f stores 2/3
Fraction g = f^3; //g stores 8/27
You may assume that exponents are nonnegative integers.
b) (25 %) Implement another version of operator^. This version of operator^ would be used by a client as follows:
Fraction f(2,3); //f stores 2/3
float g = 3.0^f; //g stores 2.08 (which is 3^(0.66667))
Please
note: in parts (a) and (b) of the above question, you may assume that the pow
function is available (i.e. pow(x,y), where x and y are floats, returns xy).
a)
Fraction
Fraction::operator^
(int Exponent) {
Fraction result;
result.numerator = pow
(numerator, Exponent);
result.denominator = pow
(denominator, Exponent);
return result;
}
b)
float
operator^ (float RHS, const Fraction& LHS) {
float exp =
(double)LHS.numerator/(double)LHS.denominator;
return pow (RHS, exp);
}
2. (22%) What is a pure virtual method? How are pure virtual methods specified syntactically?
A
pure virtual method is one that cannot be implemented because there isn’t
enough information stored in the class to do so. Syntactically, pure virtuals are specified as follows:
virtual
<return-type> <function-name> (parameters list) = 0;
3. (23%) How do programmers use abstract base classes?
According
to our textbook an abstract base class “is used only as the basis for derived
classes and thus defines a minimum interface for its descendants.”[p. 396]
4. (5%) Why would a function be made a friend of a particular class?
Friendship
grants the function so-called direct access to the private members of the
class.