Wednesday 16 August 2017

Create a class that imitates part of the functionality of the basic data type int. Call the class Int (note different capitalization). The only data in this class is an int variable. Include member functions to initialize an Int to 0, to initialize it to an int value, to display it (it looks just like an int). Overload four integer arithmetic operators (+, -, *, and /) so that they operate on objects of type Int. If the result of any such arithmetic operation exceeds the normal range of ints (in a 32-bit environment)—from 2,147,483,648 to –2,147,483,647— have the operator print a warning and terminate the program. Such a data type might be useful where mistakes caused by arithmetic overflow are unacceptable. Hint: To facilitate checking for overflow, perform the calculations using type long double. Write a program to test this class.



SOLUTION:
#include "stdafx.h"
#include "iostream"
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////
class Int
{
            private:
                        long i;
            public:
                        Int( ) :i(0)         { /*Empty Body*/ }
                        Int(int n) :i(n)    { /*Empty Body*/ }
                        void display( Int obj2, Int obj3, char ch ) const
                        {           cout << obj2.i << ch << obj3.i << " = " << i << endl;  }
                        Int operator + (Int) const;                    Int operator - (Int) const;
                        Int operator * (Int) const;                     Int operator / (Int) const;
};
//---------------------------------------------------------------------------------------
Int Int::operator + (Int temp) const
{           long r;              r = i+temp.i;                 return Int(r);                 }
Int Int::operator - (Int temp) const
{           long r;              r = i-temp.i;                  return Int(r);                 }
Int Int::operator * (Int temp) const
{           long r;              r = i*temp.i;                 return Int(r);                 }
Int Int::operator / (Int temp) const
{           long r;              r = i/temp.i;                  return Int(r);                 }
/////////////////////////////////////////////////////////////////////////////////////////
void main( )
{
            Int first, second(250), third(122);
            first = second+third;                first.display( second,third,'+' );
            first = second-third;                 first.display( second,third,'-' );
            first = second*third;                 first.display( second,third,'*' );
            first = second/third;                 first.display( second,third,'/' );
            system("pause");
}
OUTPUT:

0 comments: