C + + friend keyword

Source: Internet
Author: User

Friend: Friend class of friends function.

Friend function: does not belong to any class, just declare in the class (can be placed in private or public, no difference), tell the class, this function is your friend, of course, friends are not white: This function can access your private member variables! There is no doubt that this destroys the encapsulation of the class, there may be security problems, so what-after all, friends.

Friend class: The equivalent of making all functions inside the friend class become the friend function of another class.

For example, the following statement illustrates that Class B is a friend class of Class A:

Class a{
...
Public
Friend class B;
...
};
All member functions of Class B are friend functions of Class A that can access private and protected members of Class A.

Note When using friend classes:

(1) A friend relationship cannot be inherited.

(2) Friend relationship is one-way and not commutative. If Class B is a friend of Class A, class A is not necessarily a friend of Class B, it depends on whether there is a corresponding declaration in the class.

(3) Friend relationship does not have transitive nature. If Class B is a friend of Class A, Class C is a friend of B, Class C is not necessarily a friend of Class A, but also to see if there is a corresponding declaration in the class

(4) A friend function is not a member function of a class, so class::function name cannot be added when defined outside the class

I learned this because I used it to help my brother write homework,c++ operator overloading.

  

C + + friend keyword

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.