AFraser
AFraser

Reputation: 1006

Overloading C++ Insertion Operator (<<) for a class

I'm trying to write a class that overloads the insertion operator but in my header file I get the error.

Overloaded 'operator<<' must be a binary operator (has 3 parameters)

Here is my code:

.h file

ostream & operator<<(ostream & os, Domino dom);

.cpp file

ostream & operator<< (ostream & os, Domino dom) {
    return os << dom.toString();
}

I'm following a text book and this is what they use as an example but its not working for me.. Any suggestions?

Upvotes: 7

Views: 14439

Answers (3)

suraj rathod
suraj rathod

Reputation: 11

/*insertion and extraction overloading*/
#include<iostream>
using namespace std;
class complex
{
   int real,imag;

public:
    complex()
    {
      real=0;imag=0;
    }
    complex(int real,int imag)
    {
        this->real=real;
        this->imag=imag;
    }
    void setreal(int real)
    { 
        this->real=real; 
    }
    int getreal()
    {
       return real;
    }
    void setimag(int imag)
    { 
        this->imag=imag; 
    }
    int getimag()
    {
       return imag;
    }
    void display()
     {
      cout<<real<<"+"<<imag<<"i"<<endl;
     }

};//end of complex class

 istream & operator >>(istream & in,complex &c)
     {
         int temp;
         in>>temp;
         c.setreal(temp);
         in>>temp;
         c.setimag(temp);
         return in;
     }
 ostream &operator <<(ostream &out,complex &c)
 {
     out<<c.getreal()<<c.getimag()<<endl;
     return out;
 }

int main()
{
  complex c1;
  cin>>c1;
 // c1.display();

  cout<<c1;
  //c1.display();
  return 0;
}

Upvotes: 1

nitin_cherian
nitin_cherian

Reputation: 6655

The insertion operator (<<) can be used as a member function or a friend function.

operator << used as a member function

ostream& operator<<(ostream& os);

This function should be invoked as :

dom << cout;

In general if you are using the operator as a member function, the left hand side of the operator should be an object. Then this object is implicitly passed as an argument to the member function. But the invocation confuses the user and it does not look nice.

operator << used as a friend function

friend ostream& operator<<(ostream& os, const Domino& obj);

This function should be invoked as :

cout << dom;

In this case the object dom is explicitly passed as a reference. This invocation is more traditional and user can easily understand the meaning of the code.

Upvotes: 14

rob mayoff
rob mayoff

Reputation: 385500

You probably put your operator<< inside a class declaration. That means it takes an extra hidden parameter (the this parameter). You need to put it outside of any class declaration.

Upvotes: 15

Related Questions