The invocation of a friend function in C + + is generally divided into three ways:
1, the General friend function
2, Class A as a friend of Class B, then the member function of Class A is a friend function of Class B.
3. A member function of a class as a friend function of another class
An example of a friend function
Class A is a class of tests, and Class B is a friend class of Class A.
Class A
{
Public
A ()
{
A = 100;
b = 10;
}
Friend class B; Both public and private, often used to become a private variable, Class B is a friend of Class A class. Friend of the second way, need to take class
int Geta ()
{
return A;
}
void Printab ()
{
cout<< "A" <<a<< "B" <<b<<endl;
}
friend void SetA (A *p, int _a); Friend function is defined, friend put in front, remember friend function is put friend in front of function, friend function of the first way
Protected
Private
int A;
int b;
static int module;
};
int a::module = 10;
Class B
{
Public
void SetA (A *p, int _a);
void Displaya (A *p)
{
cout<<p->a<< "DDDDD" <<endl;
}
Protected
Private
};
The member function of the class of the friend class is the second way of the friend function
void B:: SetA (A *p, int _a)
{
P->a = _a + 100;
P->b = _a + 100;
}
The concrete realization of the first way of the common friend function
void SetA (A *p, int _a)
{
P->a = _a;
P->b = _a;
}
Using Class girl and Class boy to give examples, both the boy as a friend of the girl class, and the boy's member function is girl friend function, these two forms.
Class girl;
Class Boy
{
Public
void Display_girl (girl &x); The definition of the function of the ordinary member has not changed
//{
cout<< "Girl-name" <<x.name<< "Age" <<x.age<<endl;
//}
};
Class Girl
{
Public://This did not write pulic cause error
Girl ()
{
name = NULL;
name = new CHAR[10];
if (NULL!=name)
{
strcpy (name, "FAL");
}
Age = 26;
}
~girl ()
{
if (NULL! = name) {
Free (name);
delete [] name;
}
}
Private
Char *name;
int age;
Friend class boy; When I wrote the code didn't write class, this is a mistake, friend of the second this way
friend void Boy::d isplay_girl (girl &x); Allow member functions of one class to access the 3rd way
};
The specific implementation process of the friend function:
void boy::d isplay_girl (Girl &x)
{
cout<< "Girl-name:" <<x.name<< "\ T Age:" <<x.age<<endl;
}
Main function,
int main (void)
{
A Testa;
B Testb;
Girl Fal;
Boy Zjl;
Zjl.display_girl (FAL);
Testb.seta (&testa, 10);
cout<< "AA" <<testa.geta () <<endl;
SetA (&testa, 6);
cout<< "BB" <<testa.geta () <<endl;
return 0;
}
Remark: Learncpluseplus/functionandreload/dm03_friendly.cpp
Common usages of friend functions in C + +