I am new to C++ and I need help with a homework.
Create a Num class whose object contains a double value. Make it possible to output this value to an outflow. Redefine the arithmetic operations '+' and '-' for the class so that when one operand is of int type, the object is involved with only the whole portion of its value. For example
Num x(5.5);
cout<<"x="<<x<<endl;// return 5.5
int a=2; double b=2.5;
cout<<"a+x="<<a+x<<endl;// return 7
cout<<"x+a="<<x+a<<endl;// return 7
cout<<"b+x="<<b+x<<endl;// return 8
cout<<"x+b="<<x+b<<endl;// return 8
That is my code:
class Num
{
double _num;
public: Num(double n) : _num(n) {};
double operator+(double b)
{
if ( (_num - (int)_num) == 0 || (b - (int)b) == 0) {
return (int)_num + (int)b;
} else {
return _num + b;
}
}
double operator-(double b)
{
if ( (_num - (int)_num) == 0 || (b - (int)b) == 0) {
return (int)_num - (int)b;
} else {
return _num - b;
}
}
};
int main()
{
Num x(5.5);
cout<<"x="<<x<<endl;// return 5.5
int a=2;
double b=2.5;
//cout<<"a+x="<<a+x<<endl;// return 7
cout<<"x+a="<<x+a<<endl;// return 7
cout<<"x+b="<<x+b<<endl;// return 8
cout<<"b+x="<<b+x<<endl;// return 8 // I am receiving the error here
// cout<<"a+b="<<a+b<<endl;// return 8
//cout<<"b+x="<<b+x<<endl;// return 8
//cout<<"x+b="<<x+b<<endl;// return 8
return 0;
}
I know that I to use operator<< but I do not understand how to predefined it correctly. Can someone show me how it should look like. Thanks!