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.
#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;
}
Comments
Leave a comment