Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator<< overloading [duplicate]

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

like image 756
boaz Avatar asked Dec 21 '22 03:12

boaz


2 Answers

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.

like image 86
Lol4t0 Avatar answered Dec 24 '22 01:12

Lol4t0


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

like image 22
zar Avatar answered Dec 24 '22 03:12

zar