Practice Programs

Practice Programs can generally be solved with a short program that directly applies the programming principles presented in this chapter.

  1. Modify the definition of the class Money shown in Display 11.8 so that all of the following are added:

    1. The operators <, <=, >, and >= have each been overloaded to apply to the type Money. (Hint: See Self-Test Exercise 13.)

    2. The following member function has been added to the class definition. (We show the function declaration as it should appear in the class definition. The definition of the function itself will include the qualifier Money::.)

    Money percent(int percentFigure) const;
    //Returns a percentage of the money amount in the
    //calling object. For example, if percentFigure is 10,
    //then the value returned is 10% of the amount of
    //money represented by the calling object.
    

    For example, if purse is an object of type Money whose value represents the amount $100.10, then the call

    purse.percent(10);
    

    returns 10% of $100.10; that is, it returns a value of type Money that represents the amount $10.01.

  2. Self-Test Exercise 17 asked you to overload the operator >> and the operator << for a class Pairs. Complete and test this exercise. Implement the default constructor and the constructors with one and two int parameters. The one-parameter constructor should initialize the first member of the pair; the second member of the pair is to be 0.

    Overload binary operator+ to add pairs according to the rule

    (a, b) + (c, d) = (a + c, b + d)
    

    Overload operator analogously.

    Overload operator* on Pairs and int according to the rule

    (a, b) * c = (a * c, b * c)
    

    Write a program to test all the member functions and overloaded operators in your class definition.

  3. Self-Test Exercise 18 asked you to overload the operator >> and the operator << for a class Percent. Complete and test this exercise. Implement the default constructor and the constructor with one int parameter. Overload the + and operators to add and subtract percents. Also, overload the * operator to allow multiplication of a percent by an integer.

    Write a program to test all the member functions and overloaded operators in your class definition.