Relative to Java, Friend is a special element of C + +, a lot of textbooks on the relatively small introduction, so beginners often can not grasp quickly, this article summed up the use of friends and some places of attention for reference. Hope to be a beginner C + + friends play a little help.
Operation Steps:
1 in the Myfriend class, define the Father class as a friend
2 Write a son class inherits from Father Class
3 Create the Myfriend object in the constructor of the Father class and the son class, and define the three variables inside it
4 Create the Father object in the constructor of the Myfriend class and define the three variables inside it
Results and matters needing attention:
1 The Myfriend object created in the Father class allows direct access to all variables in the Myfriend class
2 The Myfriend object created in the Son class only allows direct access to public variables in the Myfriend class
3) from the 2nd, the friend relationship can not inherit
4 The Father object created in the Myfriend class only allows direct access to public variables in the Father class
5 from the 4th know, the friend relationship is one-way, that is, A is B friend, B is not a friend, need separate definition
The MyFriend.h page code is as follows:
#include "Father.h" class
myfriend{
friend class Quote///friend class directly this definition is OK public
:
myfriend () {
Father *p = new Father ();
P->VAR1 = 1;
P->VAR2 = 1;
P->VAR3 = 1;
}
int var1;
Protected:
int var2;
Private:
int var3;
};
The Father.h page code is as follows:
#include "MyFriend.h"
class father{public
:
Father () {
myfriend *p = new Myfriend ();
P->VAR1 = 1;
P->VAR2 = 1;
P->VAR3 = 1;
};
int var1;
Protected:
int var2;
Private:
int var3;
}
The Son.h page code is as follows:
#include "MyFriend.h"
class son:father{
Son () {
myfriend *p = new Myfriend ();
P->VAR1 = 1;
P->VAR2 = 1;
P->VAR3 = 1;}
;
}
Interested readers can debug and run the example of this article, I believe there will be a new harvest.