3

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?

Sorin
  • 908
  • 2
  • 8
  • 19
  • You know there already is a [complex number](http://en.cppreference.com/w/cpp/numeric/complex) class in the standard library? – Some programmer dude Jan 30 '13 at 10:38
  • 1
    Yes. Complex class was just a simple example and the point of the question is how can I overload the operator as a method. – Sorin Jan 30 '13 at 10:40
  • You have already found the problem - as a member function the parameters are in the wrong order. There is no way to change this. The closest you get is making it a `friend` function. – Bo Persson Jan 30 '13 at 10:46
  • 1
    http://stackoverflow.com/questions/4421706/operator-overloading, ctrl + f = stream – lucasmrod Jan 30 '13 at 10:46

3 Answers3

4

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;
}
Mr.C64
  • 41,637
  • 14
  • 86
  • 162
2

You could write a free stand operator<< function, try:

std::ostream& operator<< (std::ostream &out, const Complex& cm)
{
    out << "The number is: (" << cm.re <<", " << cm.im <<")." << std::endl;
    return out;
}
billz
  • 44,644
  • 9
  • 83
  • 100
1

You can define a global function:

void operator << (ostream& out, const Complex& complex)
{
     complex.operator<<(out);
}
Zhi Wang
  • 1,138
  • 4
  • 20
  • 34