Overloading C++ Insertion Operator (<<)

自闭症网瘾萝莉.ら 提交于 2021-02-04 17:47:43

问题


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?


回答1:


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.




回答2:


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.




回答3:


/*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;
}


来源:https://stackoverflow.com/questions/9090741/overloading-c-insertion-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!