Answer to Question #328379 in C++ for Mominul

Question #328379

Explain how overloading a unary operator is almost similar to overloading a binary operator with necessary examples and include main() function to demonstrate. Mention the differences between these two in terms of number of operands they deal with.

1
Expert's answer
2022-04-15T16:36:44-0400
#include <iostream>


using namespace std;


/*Both unary and binary operators are functions with special names.
So they may be overloaded as all other functions. The only
difference is that they require a definite number of parameters
one for a unary operator and two for a binary operator. In this case,
the operators are defined as the member of a class, the number of their
parameters reduced by one, so a unary operator gets no parameter, 
and a binary operator gets one.*/


class Distance
{
	int feet;
	int inches;
public:
	Distance(int _feet = 0, int _inches = 0)
		:feet(_feet)
	{
		if (_inches >= 12)
		{
			feet += _inches / 12;
			inches = _inches % 12;
		}
		else
			inches = _inches;
	}
	
	Distance operator++ ()
	{
		Distance tmp;
		tmp.feet = feet + 1;
		tmp.inches = inches + 1;
		if (tmp.inches >= 12)
		{
			tmp.feet += tmp.inches / 12;
			tmp.inches = tmp.inches % 12;
		}
		return tmp;
	}
	Distance operator+ (const Distance& obj)
	{
		Distance tmp;
		tmp.feet = feet + obj.feet;
		tmp.inches = inches + obj.inches;
		if (tmp.inches >= 12)
		{
			tmp.feet += tmp.inches / 12;
			tmp.inches = tmp.inches % 12;
		}
		return tmp;
	}
	void Display()
	{
		cout << "\nFeet of distance: " << feet
			<< "\nInches of distance:" << inches<<endl;
	}
		
};






int main() 
{
	Distance d(5, 11);
	d.Display();
	Distance a = ++d;
	a.Display();
	Distance b(2, 13);
	Distance c = d + b;
	c.Display();
}



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS