简体   繁体   中英

operator << operloaded API for std::endl?

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM