There are two ways of implementing operator "<<" or ">>" function in a project.
1.As a non-member function
2.As a friend
#include<iostream>
using namespace std;
class xxx{
private: int x;
public: xxx(int val=0):x(val){}
int getx(){return x;}
friend ostream& operator <<(ostream& o, xxx& x1);
};
ostream& operator<<(ostream& o, xxx& x1)
{
o<<x1.getx();
return o;
}
ostream& operator <<(ostream& o, xxx& x1)
{
o<<x1.getx();
return o;
}
int main(int argc, char *argv[])
{
xxx x1(5);
return 0;
}
Looks like both non-member and friend function have same signature when implementing, and thus i get compiler error : "error: redefinition of 'std::ostream& operator<<(std::ostream&, xxx&)' ".
Could anyone please help how to compile the above code.
Also would like to know in which situation should we use non-member "operator =" function over friend "operator =" function.