Answer to Question #333645 in C++ for Jordan

Question #333645

Write a program to overload operators in the same program by writing suitable operator member functions for following set of expressions:


O2=++O1;

O3=O2--;

O4=!O3;

O5=-O4;


[Here O1,O2,O3,O4 and O5 are objects of a class “overloading”, and this class is having one integer data member]


1
Expert's answer
2022-04-25T15:15:40-0400
#include <iostream>

using namespace std;

class Object
{
	int x;
public:
	Object() {}
	Object(int _x) :x(_x) {}
	Object operator++ ()
	{
		Object tmp;
		tmp.x = ++x;
		return tmp;
	}
	Object operator- ()
	{
		Object tmp;
		tmp.x = -x;
		return tmp;
	}
	Object operator-- (int)
	{
		Object tmp;
		tmp.x = --x;
		return tmp;
	}
	bool operator!=(Object& o)
	{
		return x != o.x;
	}


	friend ostream& operator<< (ostream&, Object&);
};


ostream& operator<< (ostream& os, Object& o)
{
	return os << "\nInfo about object: " << "x = " << o.x;
}


int main()
{
	Object O1(5);
	Object O2 = ++O1;
	cout << O2;
	Object O3 = O2--;
	cout << O3;
	Object O4(7);
	cout << O4 << endl;
	cout <<"O4 != O3 -> "<< (O4 != O3);
	Object O5 = -O4;
	cout << O5;
}

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