简体   繁体   中英

ostream& operator<< (ostream& (*pf)(ostream&));

my problem is to understand the (ostream& (*pf)(ostream&))

  1. why reference to pointer pf? In my understanding necesseary for allocation
  2. why the second (ostream&)?

I found it while reading about operator overloading.

Thanks Uwe

why reference to pointer pf? In my understanding necesseary for allocation

That is an incorrect understanding. pf is a pointer to a function. Its return type is std::ostream& and the only argument is also a std::ostream& .

why the second (ostream&)?

The function gets called using an ostream object, which gets passed by reference. The function returns a reference to the same object.

Let's take a look at the call.

std::cout << std::endl;

It is translated as:

std::cout.operator<<(std::endl);

std::ostream::operator<<(std::ostream& (*pf)(std::ostream&) can be implemented simply as:

std::ostream& std::ostream::operator<<(std::ostream& (*pf)(std::ostream& str)
{
   return pf(str);
} 

pf is a function pointer (whose single argument and return value are each a reference to ostream ), not a reference to anything.

This is used to implement manipulators like endl .

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