简体   繁体   中英

why use a non-member function?

I am learning about the friend keyword in C++ and I am wondering why have a non-member function and use the friend keyword when you can just make the non-member function a member function? I hope I made my question clear enough, thank you!

Because sometimes you need to create an overloaded operator where your class type is on the right-hand-side. This must be implemented as a free function. Classic example:

ostream& operator<<(ostream& str, my_type const& my)
{
    // print out `my` into `str`---requires `friend` if using
    // private members of `my_type`
    return str;
}

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