C ++ third operation

C ++ third operation

teaching objectives

Grasp the basic concept of friend function and its application

 

Teaching process

Definition: The friend function is a function of some, though not all members of the class members was able to access the class. Class grant it access to special friend. Usually the same developer will for reasons of technical and non-technical controls like friend and member functions (or when you want to update your class, but also the consent of the other owners of the part).

Example: The distance between the two points seek

class point{

public:

 point(int x=0,int y=0):x(x{,y(y){}

int getx(){return x;}

int gety () {return that;}

friend float dist (point & p1, point & p2); // declare a friend function

private :
int x,y;

}

float dist(point &p1,point&p2){

double x=p1.x-p2.x;

double y=p1.y-p2.y;

return static_cast<float>(sqrt(x*x+y*y));

}

  Friend function prototype is declared in point class, dist friend function outside the class declaration.

Through this example can visually recognize that the use of friend functions.      

例2:
class A{

public:

        void display(){}

         int getx(){reutrn x;}

friend B;

private :
int x;

}

class B......略

 

 

Note:
1 Friendship is not passed

2 friend relationship is unidirectional

3 Friendship is not inherited

 

Summary and Reflection

First, the friend function must be stated in the description of the class, and to begin with the keyword friend

The function prototype function followed friend, friend function described may appear anywhere in the class, including in private and public portion;

Second, friend functions of the class members can not directly access, only access object members,

Third, when you call friend function, the actual parameter should be pointed out the object to be accessed,

Fourth, a class member functions also as a friend of another class, but the class must be defined.

Guess you like

Origin www.cnblogs.com/nianshaomingtu/p/11608247.html