简体   繁体   中英

what is the difference between friend function and friend class?

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

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.

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.

友元函数用于访问类的非公共成员。一个类可以允许非成员函数和其他类通过使它们成为朋友来访问它自己的私有数据.Ariend类具有对另一个类的私有数据成员的完全访问权限成为那个班的成员。

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. enter link description here

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