Question

In: Computer Science

In the program P81.cpp and P81a.cpp, you learned to define friend functions to access the variable...


In the program P81.cpp and P81a.cpp, you learned to define friend functions to access the variable members of a class. In those programs, you used a function called add to do the addition of money (dollars and cents), and similarly did the subtraction of money using the subtract function.   Since the addition or subtraction of money required two components, it was different from an arithmetic add operation. In C++, we can overload the add operator, ''+", to do different types of addition, for example: an the addition of money in the previous programs (dollars + dollars and cents + cents). By using function overloading, we will give the power of function add to operator "+", which is also defined in the class definition.

Before we give an example of overloading operators, let's look at a new version of P81a.cpp in which the add function is defined as a friend and has the new type of AltMoney.

// P82.cpp - This program adds money of two different people
#include<iostream>
#include<cstdlib>
using namespace std;

class AltMoney
{
    public:
        AltMoney();
        AltMoney(int d, int c);

        friend AltMoney add(AltMoney m1, AltMoney m2);
        void display_money( );
    private:
        int dollars;
        int cents;
};

void read_money(int& d, int& c);

int main( )
{
     int d, c;
     AltMoney m1, m2, sum;

     sum = AltMoney(0,0);

     read_money(d, c);
     m1 = AltMoney(d,c);
     cout << "The first money is:";
     m1.display_money();

     read_money(d, c);
     m2 = AltMoney(d,c);
     cout << "The second money is:";
     m2.display_money();

     sum = add(m1,m2);
     cout << "The sum is:";
     sum.display_money();

     return 0;
}

AltMoney::AltMoney()
{
}

AltMoney::AltMoney(int d, int c)
{
       dollars = d;
       cents = c;
}

void AltMoney::display_money()
{
     cout << "$" << dollars << ".";
     if(cents <= 9)
         cout << "0"; //to display a 0 on the left for numbers less than 10
     cout << cents << endl;
}

AltMoney add(AltMoney m1, AltMoney m2)
{
     AltMoney temp;
     int extra = 0;
     temp.cents = m1.cents + m2.cents;
     if(temp.cents >=100){
         temp.cents = temp.cents - 100;
         extra = 1;
      }
      temp.dollars = m1.dollars + m2.dollars + extra;

      return temp;
}

void read_money(int& d, int& c)
{
     cout << "Enter dollar \n";
     cin >> d;
     cout << "Enter cents \n";
     cin >> c;
     if( d < 0 || c < 0)
     {
            cout << "Invalid dollars and cents, negative values\n";
            exit(1);
      }
}

In this program the add is defined as a friend and has the type AltMoney as well.

Now, let's overload the "+" operator so that is does what the function add is doing.

Here are the changes that you need to make: (red font)

1) In class AltMoney:
class AltMoney
{
    public:
        AltMoney();
        AltMoney(int d, int c);

        friend AltMoney operator +(AltMoney m1, AltMoney m2);
        void display_money( );
    private:
        int dollars;
        int cents;
};

2) In the main:

     sum = m1+m2;

3) In the function definition
AltMoney operator +(AltMoney m1, AltMoney m2)
{
     AltMoney temp;
     int extra = 0;
     temp.cents = m1.cents + m2.cents;
     if(temp.cents >=100){
         temp.cents = temp.cents - 100;
         extra = 1;
      }
      temp.dollars = m1.dollars + m2.dollars + extra;

      return temp;
}

By making these changes, you can now add two objects of type AltMoney. Note that you may overload "+" in another class definition. Depending on how you have defined it, "+" operation may have different meanings in such cases.

Exercise 8.2
First make the above changes in P82.cpp and call the new program ex82.cpp. Compile and run the program and make sure it produces the correct results. Here is what you need to do for the exercise:

    Overload the % operator such that every time you use it, it takes two objects of type AltMoney as its arguments and returns:
            a) 5% of the difference between the income and expenditure, if income is larger than the expenditure
            b) -2% if the the expenditure is larger than the income.
            c) 0 if the expenditure is the same as income
Note that, by doing this, you are required to overload the greater than sign (>), the smaller than sign (<), and the == sign.

Solutions

Expert Solution

// C++ program to implement overloaded operators using friend functions

#include <iostream>

#include<cstdlib>

using namespace std;

class AltMoney

{

    public:

        AltMoney();

        AltMoney(int d, int c);

        friend AltMoney operator +(AltMoney m1, AltMoney m2);

        // new overloaded operators

        friend AltMoney operator %(AltMoney income, AltMoney expenditure);

        friend bool operator>(AltMoney m1, AltMoney m2);

        friend bool operator<(AltMoney m1, AltMoney m2);

        friend bool operator==(AltMoney m1, AltMoney m2);

        void display_money( );

    private:

        int dollars;

        int cents;

};

void read_money(int& d, int& c);

int main( )

{

     int d, c;

     AltMoney m1, m2, sum, percent;

     sum = AltMoney(0,0);

     read_money(d, c);

     m1 = AltMoney(d,c);

     cout << "The first money is:";

     m1.display_money();

     read_money(d, c);

     m2 = AltMoney(d,c);

     cout << "The second money is:";

     m2.display_money();

     sum = m1+m2;

     cout << "The sum is:";

     sum.display_money();

     percent = m1%m2;

     cout<<"The percent is : ";

     percent.display_money();

     return 0;

}

AltMoney::AltMoney()

{

       dollars = 0;

       cents = 0;

}

AltMoney::AltMoney(int d, int c)

{

       dollars = d;

       cents = c;

}

void AltMoney::display_money()

{

     cout << "$" << dollars << ".";

     if(cents <= 9)

         cout << "0"; //to display a 0 on the left for numbers less than 10

     cout << cents << endl;

}

AltMoney operator +(AltMoney m1, AltMoney m2)

{

     AltMoney temp;

     int extra = 0;

     temp.cents = m1.cents + m2.cents;

     if(temp.cents >=100){

         temp.cents = temp.cents - 100;

         extra = 1;

      }

      temp.dollars = m1.dollars + m2.dollars + extra;

      return temp;

}

void read_money(int& d, int& c)

{

     cout << "Enter dollar \n";

     cin >> d;

     cout << "Enter cents \n";

     cin >> c;

     if( d < 0 || c < 0)

     {

            cout << "Invalid dollars and cents, negative values\n";

            exit(1);

      }

}

// returns a percentage of difference between income and expenditure

AltMoney operator %(AltMoney income, AltMoney expenditure)

{

       AltMoney temp;

       int income_in_cents = income.dollars*100 + income.cents; // get the income in cents

       int exp_in_cents = expenditure.dollars*100 + expenditure.cents; // get the expenditure in cents

       int diff_in_cents;

       if(income > expenditure)

       {

             diff_in_cents = income_in_cents - exp_in_cents;

             int req_result = diff_in_cents*0.05;

             temp.dollars = req_result/100;

             temp.cents = req_result%100;

       }

       else if(income < expenditure)

       {

             diff_in_cents = exp_in_cents - income_in_cents;

             int req_result = diff_in_cents*0.02;

             temp.dollars = req_result/100;

             temp.cents = req_result%100;

       }

       return temp;

}

// returns true if m1 is greater than m2 else false

bool operator>(AltMoney m1, AltMoney m2)

{

       if(m1.dollars > m2.dollars)

             return true;

       else if(m1.dollars < m2.dollars)

             return false;

       else

       {

             if(m1.cents > m2.cents)

                    return true;

             else

                    return false;

       }

}

// returns true if m1 is less than m2 else false

bool operator<(AltMoney m1, AltMoney m2)

{

       if(m1.dollars < m2.dollars) // if dollars of m1 < dollars of m2 , then return true

             return true;

       else if(m1.dollars > m2.dollars) // check if dollars of m1 > dollars of m2, then return false

             return false;

       else // check the cents of m1 and m2 if dollars are equal

       {   

             if(m1.cents < m2.cents)

                    return true;

             else

                    return false;

       }

}

// returns true if m1 is equal to m2 else false

bool operator==(AltMoney m1, AltMoney m2)

{

       return((m1.dollars == m2.dollars) && (m1.cents == m2.cents)); // check if both dollars and cents of m1 and m2 are equal

}

//end of program

Output:


Related Solutions

discuss and define the concept of total differential for one functions of one variable and functions...
discuss and define the concept of total differential for one functions of one variable and functions of n variables. give examples of its application in economics
Modeling with Functions In this course you have learned the characteristics of different types of functions...
Modeling with Functions In this course you have learned the characteristics of different types of functions and have practiced solving application problems involving modeling with these functions. For each scenario below, decide what type of function would best model the situation. Explain why you chose that type of function. Show your work in writing the function to model the situation. Be sure to state what the independent variable represents. Then use your model to answer the questions for that scenario....
First make the changes in P82.cpp and call the new program ex82.cpp. Compile and run the...
First make the changes in P82.cpp and call the new program ex82.cpp. Compile and run the program and make sure it produces the correct results. Here is what you need to do for the exercise:     Overload the % operator such that every time you use it, it takes two objects of type AltMoney as its arguments and returns:             a) 5% of the difference between the income and expenditure, if income is larger than the expenditure             b) -2%...
Part 1 Write a C++ program in which you define the following logical functions: 1) contradictory...
Part 1 Write a C++ program in which you define the following logical functions: 1) contradictory function (¬?) 2) logical and (? ∧ ?) 3) logical inclusive or (? ∨ ?) 4) implication function (? → ?) 5) biconditional (? ↔ ?) 6) logical exclusive or (? ⨁ ?) You can find the logical definitions for the above functions as given by Bertrand Russell in your text. You need to write a method (function) for each corresponding logical function. The...
Provide a description of what you learned on Patient Privacy: A Guide for Providers: -Access to...
Provide a description of what you learned on Patient Privacy: A Guide for Providers: -Access to Medical Services -Amendment - Rights and Restrictions Provide a description of what you learned on HIPAA and You: Building a Culture of Compliance: - HIPAA Security Standards - Policies and Procedures - Monitoring and Reporting Provide a description of what you learned in: Examining Compliance with the HIPAA Privacy Rule: -What businesses are covered under the HIPAA Privacy Rule? - What health information is...
Explain to a friend what you have learned about documentation and evidence. Be sure to detail...
Explain to a friend what you have learned about documentation and evidence. Be sure to detail why we need it and how we get it. Do not get too technical; they do not understand accounting or auditing. You may use a combination of formal terms, examples, and resources to support your answer.
what should this program do? Write a program (Lab8.cpp) that will ask the user for two...
what should this program do? Write a program (Lab8.cpp) that will ask the user for two file names. You will read the characters from each file and put them in separate queues. Then, you will read each character from each queue and compare it. If every character from both queues is the same, you will print “The files are identical.” Otherwise, you will print “The files are not identical.” Step-by-Step Instructions Create a character queue (named queue1) using the Standard...
You have learned that protein is important for body functions and that most of us get...
You have learned that protein is important for body functions and that most of us get more than the RDA for protein. Why do you think the high protein diets such as The Zone and The Adkins Diet are so appealing to people who desire weight loss? Are there potential advantages and disadvantages to these diets? What would you counsel someone who was using one of these diets?
A close friend sustains a major knee injury and needs surgery. What have you learned that...
A close friend sustains a major knee injury and needs surgery. What have you learned that can help you prepare your friend for surgery and recovery?
While talking to your friend about your week, you mentioned that you had just learned about...
While talking to your friend about your week, you mentioned that you had just learned about standard costing which plays a vital role in variance analysis. This topic interested your friend, who runs a bakery and wants to learn what he or she would need to do to set up a standard costing system for the bakery. This gives you an opportunity to share your new knowledge with your friend. What would you tell your friend about standard costing?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT