C ++ input operator overload (<<)

I am trying to write a class that overloads the insert statement, but I get an error in my header file.

 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 follow the tutorial and this is what they use as an example, but it does not work for me .. Any suggestions?

+4
source share
4 answers

You will probably place your operator<< inside the class declaration. This means that an additional hidden parameter is required ( this parameter). You must put it outside any class declaration.

+14
source

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

operator <is used as a member function

 ostream& operator<<(ostream& os); 

This function should be called as:

 dom << cout; 

In general, if you use an operator as a member function, the left side of the operator should be an object. This object is then implicitly passed as an argument to the member function. But the challenge confuses the user, and he does not look very good.

operator <is used as a function of a friend

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

This function should be called as:

 cout << dom; 

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

+10
source
 /*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; } 
0
source

Hello, I want to overload the insert statement, as we do for the class. But now I want to overload this >> with a variable, Actually I want to perform some more operations / functions when we generate any value from users ....... So how can I solve this?

0
source

Source: https://habr.com/ru/post/1394117/


All Articles