C + + friend class, friend function

Source: Internet
Author: User

//Friend function Friend class#include <iostream>using namespacestd;classpointb{ Public: FriendclassPOINTC; //class Pointc is a friend of class pointb--meaning that the class Pointc object can invoke all members of POINTB    voidTest () {; }Private:    intx; inty;};classpointc{ Public:    voidPrintfpointb () {//call the private property of its friend classcout << pb.y <<Endl; //call the member function of POINTBPB.    Test (); }Private: POINTB pb;};classpointa{ Public:    //friend functionFriendvoidFriendfun (pointa*pin); intGeta () {returnA; }    intGetb () {returnb; }Private:    intA; intb;};//Friend Connections//Const (C-language) counterfeit//register CPU side of the Small eunuch (register)//typedef mixed King (alias)//friend function//A friend must have a parameter that is the object pointer of the class in which the friend function is located (otherwise it cannot access the private properties of the object)//A friend function is a global function//encapsulation of class with friend function failurevoidFriendfun (pointa*pin) {    //private members of a class can be accessed directlyPin->a =Ten; Pin->b = -;}voidProtecta () {Pointa*P1 =NewPointa ();    Friendfun (p1); cout<<"a="<< P1->geta () <<"; b="<< P1->getb () <<Endl; if(p1!=NULL) {        DeleteP1; }}voidMain () {protecta (); System ("Pause");}

C + + friend class, friend function

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.