Answer to Question #287959 in C++ for Malik

Question #287959

Create a class which only works for absolute numbers, if it

encounters any negative occurrence, then it throw an exception to its

handler and display errors.


1
Expert's answer
2022-01-16T13:04:23-0500
#include<iostream>

using namespace std;

class AbsoluteNum
{
	int num;
public:
	AbsoluteNum(int _num)
	{
		try
		{
			if (_num < 0)
				throw "Negative number!";
			else
				num = _num;
		}
		catch (const char* e)
		{
			cout << "\nError! " << e;
		}
		
	}
	AbsoluteNum& operator=(int _num)
	{
		try
		{
			if (_num < 0)
				throw "Negative number!";
			else
				num = _num;
		}
		catch (const char* e)
		{
			cout << "\nError! " << e;
		}
		return *this;
	}
	friend ostream& operator<<(ostream& os, const AbsoluteNum& an);
};


ostream& operator<<(ostream& os, const AbsoluteNum& an)
{
	os << an.num;
	return os;
}


int main()
{
	AbsoluteNum a(5);
	cout <<"Absolute num a: "<< a;
	AbsoluteNum b(-1);
	AbsoluteNum c(1);
	cout << "\nAbsolute num c: " << c;
	c = -2;
	c = a;
	cout << "\nAbsolute num c: " << c;
}

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