Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a simple class (DoStuff) containing an int, and overload the operator+ as

ID: 3785721 • Letter: C

Question

Create a simple class (DoStuff) containing an int, and overload the operator+ as a member function. Also, provide a print() member function that takes an ostream& as an argument and prints to that ostream&. Add a binary operator- and operator+ to the class as member functions. You should be able to use the objects in complex expressions such as a + b – c. Now add the operator++ and operator--, both prefix and postfix versions. Overload the << operator to provide the same functionality as the print() member function. Test the class to show that all requirements work correctly. IN C++ I am reposting this question because the solution I got the first time was incorrect and full of errors.

Explanation / Answer

#include <iostream>
using namespace std;


class DoStuff
{
   private:
   int i;
  
   public:
   DoStuff()   //default constructor
   {
       i=0;
   }
   DoStuff(int i) //parameterized constructor
   {
       this->i = i;
   }
   DoStuff operator+(DoStuff obj)   //operator overloading +
   {
       DoStuff temp;
       temp.i = i + obj.i;
       return temp;
   }
   DoStuff operator-(DoStuff obj) //operator overloading -
   {
       DoStuff temp;
       temp.i = i - obj.i;
       return temp;
   }
   void print(ostream& os) // print function with ostream&
   {
       os<<this->i<<" ";
   }
   DoStuff operator++()     //operator overloading ++
   {
       DoStuff temp;
       ++i;
       temp.i = i;
       return temp;
      
   }
   DoStuff operator--()   //operator overloading --
   {
       DoStuff temp;
       --i;
       temp.i = i;
       return temp;
      
   }
   friend ostream & operator << (ostream &out, const DoStuff &d);//friend function
};
ostream & operator << (ostream &out, const DoStuff &d)
{
    out << d.i;
  
    return out;
}
int main()
{
   DoStuff a(4),b(6),c(2); //objects
   cout<<(a+b-c);    //evaluate expressions
   cout<<endl;
  
   a.print(cout);
   b.print(cout);
   c.print(cout);
   return 0;
}

output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote