<< operator overloading as a class method in c++

c++, operator-overloading

Solution

I would just use the usual C++ pattern of free function. You can make it `friend` to your `Complex` class if you want to make `Complex` class's private data members visible to it, but usually a complex number class would expose public getters for real part and imaginary coefficient.

class Complex
{
  ....

   friend std::ostream& operator<<(std::ostream &out, const Complex& c);
private:
   double re;
   double im;
};

inline std::ostream& operator<<(std::ostream &out, const Complex& c)
{
    out << "The number is: (" << c.re << ", " << c.im << ").\n";
    return out;
}

Problem

I want to overload the << operator for my class Complex. The prototype is the following: ``` void Complex::operator << (ostream &out) { out << "The number is: (" << re <<", " << im <<")."<<endl; } ``` It works, but I have to call it like this: object << cout for the standart output. What can I do to make it work backwards, like cout << object? I know that the 'this' pointer is by default the first parameter sent to the method so that's why the binary operator can work only obj << ostream. I overloaded it as a global function and there were no problems. Is there a way to overload the << operator as a method and to call it ostream << obj?

Original source

Related problems