I am getting error in this code while converting the member data of the class Int
to long double
in the conversion operators. But I don't understand why this happens?
#include<iostream>
using namespace std;
class Int
{
private:
int number;
public:
Int() : number(0) // no argument constructor
{ }
Int( int i) : number(i) // 1-argument constructor
{ }
void putInt() // display Int
{ cout << number; }
void getInt() // take value from the user
{ cin >> number; }
operator int() // conversion operator ( Int to int)
{ return number; }
Int operator + ( Int a)
{ return checkit( long double (number) + long double (a)) ; } // performs addition of two objects of type Int
Int operator - ( Int a)
{ return checkit(long double (number) - long double (a) ); } //performs subtraction of two objects of type Int
Int operator * (Int a)
{ return checkit( long double (number) * long double (a) ); } // performs multiplication of two objects of type Int
Int operator / (Int a)
{ return checkit( long double (number) / long double (a) ); } // performs division of two objects of type Int
Int checkit( long double answer)
{
if( answer > 2147483647.0L || answer < - 2147483647.0L)
{ cout << "\nOverflow Error\n";
exit(1);
}
return Int ( int(answer));
}
};
int main()
{
Int numb1 = 20;
Int numb2 = 7;
Int result, cNumber;
result = numb1 + numb2;
cout << "\nresult = "; result.putInt(); //27
result = numb1 - numb2;
cout << "\nresult = "; result.putInt(); //13
result = numb1 * numb2;
cout << "\nresult = "; result.putInt(); // 140
result = numb1 / numb2;
cout << "\nresult = "; result.putInt(); // 2
cNumber = 2147483647;
result = numb1 + cNumber; // overflow error
cout << "\nresult = "; result.putInt();
cNumber = -2147483647;
result = numb1 + cNumber; // overflow error
cout << endl;
return 0;
}
In the operator overloading code for the +
, -
, *
and /
operators, I am getting errors of:
expected primary expression before 'long'
I don't understand why this happens.