C + +: Friend class

Source: Internet
Author: User

First, the article for the reason

The last one wrote a friend function, this time write a sister chapter, continue to delve into the friend class.

Second, the definition

All member functions of a friend class are friend functions that also have a class. Have access to the hidden information in a class that contains private members and protected members.

When you want a class to be able to access a private member of a class, you can declare the class as a class of friend. The statement format that defines the friend class is as follows:

Friend class name;

Here: friend and class are keywords, and the class name must be a defined class in the program.

Iii. examples
#include <iostream>using namespace STD;classradius{friend classCircle;//Declare a friend class of circle as Radius    friend voidShow_r (Radius &n);//Declare show_r as friend function Public: Radius (intX) {r = x;} ~radius () {}Private:intR;};voidShow_r (Radius &n) {cout<<"The radius of the circle is:"<<n.r<<endl;//Call the RADIUS object's private member variable R}classcircle{ Public: Circle () {} ~circle () {}DoubleArea (Radius a) {s = A.R * A.R *3.1415926;//Call the RADIUS object's private member variable R    returns;}Private:Doubles;};intMainintargcChar*argv[]) {Radius Objradius (9);    Circle objcircle; Show_r (Objradius);cout<<"area is:"<<objcircle.area (Objradius) <<endl;return 0;}

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.