C/c++:c++ Friend class

Source: Internet
Author: User


C + + friend class:

Under normal circumstances, a class is not accessible to private members of another class. Just like this:


#include <iostream>class a{private:    int a;public:    A () {        a = 1;    }}; Class B:public A{public:    B () {        std::cout << A << std::endl;    }}; int main () {    B p;    P ();    return 0;}

This is an error: main.cpp|6|error: ' int a::a ' is private| In other words, A is private and B is not accessible.

At this point, we are going to use the concept of the friend class.

<span style= "FONT-SIZE:18PX;" > #include <iostream>class a{    friend class b;//specifies a friend of B as a. Private:    int a;public:    A () {        a = 1;    }}; Class B:public A{public:    B () {        std::cout << A << std::endl;    }}; int main () {    B p;    return 0;} </span>

At this point, B will be able to access the private members of a. Even if B does not inherit to a, it can be accessed. Just like this:

<span style= "FONT-SIZE:18PX;" > #include <iostream>class a{    friend class b;//specifies a friend of B as a. Private:    int a;public:    A () {        a = 1;    }}; Class B{public:    B () {        a A;        Std::cout << a.a << std::endl;    }; int main () {    B p;    return 0;} </span>


In fact, however, in the development process, the programmer seldom uses the friend class, because it makes the two classes directly related to too close.



PS: Beginner C + +, there is nothing wrong place, be sure to tell me _ (: З"∠) _. I am good at correcting my studies, and I will not mislead others.


C/c++:c++ Friend class

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.