operator<< overloading

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


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.


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

Personally, I prefer to stay away from friend ship 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);
}

declare it as friend like this:

friend ostream& Complex::operator<<(ostream& out,const Complex& b)
{ ... }

edit >>

I believe the above is not right because declaring friend in .cpp is a wrong syntax, it must be declared as friend in .h file in class definition and that simply makes it a global function.

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

  friend std::ostream& operator<< (std::ostream& s, const Complex& c)
  {
     return c.output(s);
  }
};

More on friend here

链接地址: http://www.djcxy.com/p/12704.html

上一篇: 在C ++中为类创建赋值(=)运算符

下一篇: 运算符<<重载