Chapter. Sams Publishing Object-Oriented Programming in C++
Werbung
Werbung
24 3087 App G 11/29/01 2:22 PM Page 942
942
Appendix G time3 = time1 + time2; //add two times cout << “\ntime3 = “; time3.display(); //display result cout << endl; return 0;
}
4.
// ex8_4.cpp
// overloaded arithmetic operators work with type Int
#include <iostream> using namespace std;
#include <process.h> //for exit()
//////////////////////////////////////////////////////////////// class Int
{ private: int i; public:
Int() : i(0) //no-arg constructor
{ }
Int(int ii) : i(ii) //1-arg constructor
{ } // (int to Int) void putInt() //display Int
{ cout << i; } void getInt() //read Int from kbd
{ cin >> i; } operator int() //conversion operator
{ return i; } // (Int to int)
Int operator + (Int i2) //addition
{ return checkit( long double(i)+long double(i2) ); }
Int operator - (Int i2) //subtraction
{ return checkit( long double(i)-long double(i2) ); }
Int operator * (Int i2) //multiplication
{ return checkit( long double(i)*long double(i2) ); }
Int operator / (Int i2) //division
{ return checkit( long double(i)/long double(i2) ); }
Int checkit(long double answer) //check results
{ if( answer > 2147483647.0L || answer < -2147483647.0L )
{ cout << “\nOverflow Error\n”; exit(1); } return Int( int(answer) );
}
};
//////////////////////////////////////////////////////////////// int main()
{
Herunterladen
Werbung