C + + Friend

Source: Internet
Author: User

Friend is a friend and friend of the class.

Friend function: A friend function of a class can access the private members of the class

We can use the member functions of one class (including constructs, destructors) as friend functions of another class. As follows

classCcar;//declare the Ccar class in advance so that the following Cdriver class uses theclassCdriver { Public:    voidModifycar (Ccar *pcar);//Modified Car};classCcar {Private:    intPrice ; FriendintMostexpensivecar (Ccar cars[],intTotal);//declare as FriendFriendvoidCdriver::modifycar (Ccar *pcar);//Declare friend};voidCdriver::modifycar (CCAR *Pcar) {Pcar->price + = +;}intMostexpensivecar (Ccar cars[],intTotal ) {    intTmpmax =-1;  for(inti =0; I < total; ++i) {if(Cars[i].price >Tmpmax) {Tmpmax=Cars[i].price; }    }    returnTmpmax;}intMain () {return 0;}

Friend class

A is a friend of B, then A's member function can access the private member of B.

Note: Relationships between friend classes cannot be passed and cannot be inherited.

The following code

classCcar {Private:    intPrice ; FriendclassCdriver;//declare cdriver as friend class};classCdriver { Public: Ccar MyCar; voidModifycar () {//Modified CarMycar.price + = +; }};intMain () {return 0;}

C + + Friend

Related Article

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.