C++ friend function and copy constructor details

  • 2020-04-02 02:26:18
  • OfStack

I. friend function

1. Overview of friend functions:

(1) friend functions are ordinary functions defined outside a class.
Friend functions are defined the same as normal functions; The ordinary function must be declared as a friend within the class.

(2) friend function is not a member function.
It cannot be called through an object, but directly. Friend functions can access public, protected, and private members of a class, but they must be accessed through objects, object Pointers, or object references.

2. Declaration of friend functions:

Friend return value type function name (parameter list);
You simply place the declaration in the public part of the class.


class Point
{
double x, y;
public:
Point(){x = 0.0; y = 0.0;}
Point(double xx, double yy){x = xx; y = yy;}
friend double distance(Point, Point);//Declares the distance function as a friend function
};
double distance(Point my1, Point my2)
{
return sqrt((my1.x-my2.x)*(my1.y-my2.y));
}

3. Friend function in the definition of the definition of the ordinary function, the front does not add friend, declared in the class, must add friend.
Private, public, and protected members can be accessed within the scope of the object in which the friend function takes effect.
The main function cannot be declared as the friend function of the class, and the main function can only be called.

Ii. Copy constructor

1. Copy constructor overview:

(1) the copy constructor is a constructor, which belongs to the member function of the class (generally defined as public); The same as the class name but no return value; When an object is created, it is called if the object's initialization value is another of its kind (the assignment is not called).

(2) copy the constructor declaration

Class name :: class name (class name & object reference name); Or another way to declare it
Class name :: class name (const class name & object reference name)
Note: the copy constructor has only one argument, and the argument must be a reference to an object. Each class actually has to have a copy constructor, and if it is not explicitly defined, the system will automatically define and set its property to public.

2. Sample program:


class Point
{
int x, y;
public:
Point(){x = 0; y = 0;}
Point(int xx, int yy){x = xx; y = yy;}
Point(Point &pf){x = pf.x; y = pf.y;}//Copy constructor declaration can omit the first class name and ::
};
Point(Point &pf)
{
*this = pf; //Complete copy construction
}
int main()
{
Point p1; //Invokes the argument - free construct
Point p2(3, 4); //Call structure
Point p3(p2); //Invoke copy construction
}

Note: if const is not used, the presence of pf.x=8 is legal, but const is illegal. In addition, the referenced pf is also released.


Related articles: