What is friend ostream

前端 未结 4 550
北海茫月
北海茫月 2021-01-03 02:24

I\'m a bit confused about what exactly this line of code means in my header file.

friend ostream & operator << (ostream &, const something &         


        
4条回答
  •  长发绾君心
    2021-01-03 03:13

    As mentioned in many places, friend is a bypass to the normal protection mechanisms of C++ - it allows the function in question to access protected/private members, which normally only class members can do.

    You'll often seen operators declared friends, because operators are never inside the class itself, but often need to modify something in the class and/or access private information. I.E. you may not want an external function to be able to muck with your internal pointers etc, but you may want to be able to print them out for status etc. You don't see them used very often otherwise - technically, it breaks encapsulation - but operators are kind of a special case.

提交回复
热议问题