Reputation: 45
I am really confused while overloading << operator as friend function.
This line works fine
cout << endl;
But this line gives compilation issue. Why ??
operator <<(cout, endl);
Below is the sample code
class Logger
{
int _id;
string _name;
public:
Logger(int id, string name):_id(id),_name(name){
cout<<"Constructor"<<endl;
}
~Logger(){
cout<<"destructor"<<endl;
}
friend ostream& operator <<( ostream& out,Logger& log);
};
ostream& operator << (ostream& out,Logger& log)
{
out<<log._id<<" "<<log._name;
return out;
}
And What is the need of return statment ? Without return also the below statment works fine.
cout<< log << endl << endl << log2 << endl << log3 << endl;
Upvotes: 0
Views: 54
Reputation: 76245
The operator<<
that takes a stream manipulator is a member function of basic_ostream
. You can't call it as if it were a free function; you have to call it as a member function:
std::cout.operator<<(std::endl)
On the other hand, the stream inserter that takes a std::string
is a free function, and you can call it with the usual function call:
std::string text = "Hello, world";
operator<<(std::cout, text);
but not as a member function.
std::endl
is usually the wrong thing to use; '\n'
ends a line, without the extra stuff that std::endl
does.
Upvotes: 1