Friend function and friend class in C + +

Source: Internet
Author: User

#include <iostream>
using namespace Std;

Class MyClass1
{
Public:
MyClass1 (): N (0) {};

void Setn (int tmpn) {THIS->N=TMPN;}

void Show () {Cout<<n<<endl;}


Private

Friend class
Friend class MyClass2;
Use the friend function to change the value of the member variable n in the MyClass1
friend void SetnF1 (MyClass1 & Tmpclass,int TMPN);

int n;
};

Class MyClass2
{
Public
Use member functions in a friend class to change the value of member variable N in myclass1
void SetnF2 (MyClass1 & Tmpclass,int tmpn) {TMPCLASS.N=TMPN;}

};

void SetnF1 (MyClass1 & Tmpclass,int TMPN)
{
TMPCLASS.N=TMPN;
}

int main ()
{
MyClass1 P1;
MYCLASS2 P2;
cout<< "P1 member variable n defaults to:" <<endl;
P1.show ();

cout<< "after setting using MyClass1 's own member function:" <<endl;
P1.SETN (100);
P1.show ();

cout<< "after setting with friend function:" <<endl;
SetnF1 (p1,101);
P1.show ();

cout<< "After setting with friend class:" <<endl;
P2.setnf2 (p1,102);
P1.show ();

return 0;
}

Execution Result: (click image to enlarge)

Friend function and friend class in C + +

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.