what is the difference between friend function and friend class?

江枫思渺然 提交于 2019-12-23 09:57:19

问题


what is the difference between friend function and friend class? and where should be use of friend keyword?


回答1:


In short, one is a class and one is a function. For the function, just that one function gets access to private members. For a class, the whole class and all its functions get access to the private members of the befriended class.

The friend keyword is used to grant access to private data members. At times you may need a helper class or a complimentary class to access the private members of a different class. For functions, a common example is an operator overload. Perhaps you want to overload the + operator. You may make an operator+ function declared outside the class (so it can be called without an object) and it will need to access the private class data.

Check out this site for a detailed description of both and how to use them.




回答2:


Friend function

  1. The friend keyword is used for declaration.
  2. While writing definition of function, the friend keyword is not required.
  3. Through a friend function, we can allow outside functions to access the class members.

Friend class

  1. For the declaration of a friend class, the friend keyword is used: friend class a;
  2. While writing a class, the friend keyword is not required.
  3. With a friend class we can access the members of one class into another.



回答3:


A friend function is used for accessing the non public member of a class.A class can allow non-member function and other classes to access its own private data by making them friend A Friend class has full access of private data members of another class without being member of that class.




回答4:


Friend keyword can be used with function and class as well.

This means if a class is declared as a friend it has access to all data members (private & public) of class which has declared it as a friend.

I have already explained the difference between them with Examples in my blog: Difference between friend function and friend class




回答5:


1)Friends function is used to access the private data variable of classes where member function is used to access private data variable of same class.

2)u can call the friends function in main function without any object but to call member function of class u just need to create object of same class.

3)friends function can be treated as non-member function but member function is not a treated as non member function of class.



来源:https://stackoverflow.com/questions/3793063/what-is-the-difference-between-friend-function-and-friend-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!