7

Possible Duplicate:
Operator overloading

I didn't find any thing that could help me in this subject... I'm trying to over load the << operator, this is my code:

 ostream& Complex::operator<<(ostream& out,const Complex& b){
    out<<"("<<b.x<<","<<b.y<<")";
    return out;
}    

this is the declaration in the H file:

 ostream& operator<<(ostream& out,const Complex& b);

I get this error: error: std::ostream& Complex::operator<<(std::ostream&, const Complex&) must take exactly one argument

what and why I'm doing wrong? thanks

Community
  • 1
  • 1
boaz
  • 920
  • 1
  • 13
  • 32

3 Answers3

10

your operator << should be free function, not Complex class member in your case.

If you did your operator << class member, it actually should take one parameter, which should be stream. But then you won't be able to write like

std::cout << complex_number;

but

complex_number << std::cout;

which is equivalent to

complex_number. operator << (std::cout);

It is not common practice, as you can note, that is why operator << usually defined as free function.

Lol4t0
  • 12,444
  • 4
  • 29
  • 65
1
class Complex
{
    int a, b;
public:
    Complex(int m, int d)
    {
        a = m; b = d;
    }
    friend ostream& operator<<(ostream& os, const Complex& complex);
};

ostream& operator<<(ostream& os, const Complex& complex)
{
    os << complex.a << '+' << complex.b << 'i';
    return os;
}

int main()
{
    Complex complex(5, 6);
    cout << complex;
}

More info here

zar
  • 11,361
  • 14
  • 96
  • 178
0

As noted, the streaming overloads need to to be free functions, defined outside of your class.

Personally, I prefer to stay away from friendship and redirect to a public member function instead:

class Complex
{
public:
   std::ostream& output(std::ostream& s) const;
};

std::ostream& operator<< (std::ostream& s, const Complex& c)
{
   return c.output(s);
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82