-3

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!

ALK
  • 103
  • 1
  • 11
  • 3
    You don't tell the compiler how to `cout << x`. – L. F. Jun 07 '19 at 09:25
  • I've tried to unfuck your error message. At least parts of it make sense now, but next time please just copy/paste the compiler output as is. – melpomene Jun 07 '19 at 09:33
  • Your task says "*Make it possible to output this value to an outflow.*" That's `operator<<`. It's missing from your code. – melpomene Jun 07 '19 at 09:33

1 Answers1

6

You need to define an operator<< outside of your class which takes the std::ostream as the left parameter and your own Num class as the right.

How to properly overload the << operator for an ostream?

Bart
  • 1,405
  • 6
  • 32
  • Thanks, but I am stupid and still do not understand how to predefined the operator<< to work for me. The link does not help me at all! – ALK Jun 07 '19 at 10:48