You get a bonus - 1 coin for daily activity. Now you have 1 coin

1.7. Friends of classes 1.7.2. Friendly class

Lecture



A class may be friendly to another class. This means that all the component functions of a class are friendly to another class. A friendly class must be defined outside the body of the class “providing friendship”.

For example,

class X2 {friend class X1; . . .};

class X1

{. . .

void f1 (...);

void f2 (...);

. . .

};

// In this example, functions f1 and f2 of class X1 are friends of class X2, although they

// described without the friend specifier.

Example 1.7.2

Consider the point class — a point in n-dimensional space and its friendly vector class — the radius vector of a point (“vector with the origin at the origin of n-dimensional space”). In the vector class, we define a function for determining the norm of a vector, which is calculated as the sum of the squares of the coordinates of its end.

clas s point

{int N; // dimension

double * x; // pointer to an array of coordinates

friend class vector;

public:

point (int n, double d = 0.0);

};

point:: point (int n, double d)

{N = n;

x = new double [N];

for (int i = 0; i <N; i ++) x [i] = d;

}

class vector

{double * xv;

int N;

public:

vector (point, point);

double norma ();

};

vector:: vector (point begin, point end)

{N = begin.N;

xv = new double [N];

for (int i = 0; i <N; i ++) xv [i] = end.x [i] –begin.x [i];

}

double vector:: norma ()

{double dd = 0.0;

for (int i = 0; i <N; i ++) dd + = xv [i] * xv [i];

return dd;

}

void main (void)

{point A (2,4.0);

point B (2,2.0);

vector V (A, B);

cout << V.norma ();

}

// It will be displayed - 8.

The disadvantage of the proposed point class is that the values ​​of all coordinates of the point x [i] are the same. In order for them to be arbitrary and different, it is necessary to define a constructor as a function with a variable number of parameters, for example:

point:: point (int n, double d, ...)

{

N = n;

x = new double [N];

double * p = & d;

for (int i = 0; i <N; i ++) {x [i] = * p; p ++;}

}

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "C ++ (C plus plus)"

Terms: C ++ (C plus plus)