Friend Features

For example, in Friends Functions.
How is this true?

"Note that neither in the duplicate () declaration, nor in its later use in main (), we considered a duplicate member of the CRectangle class. This is not so. It simply has access to its private and protected members without a member."

The duplicate is declared in the public section of CRectangle. How is it not a member function and set_values?

Is this a good example? Any better ones if not?

+3
source share
4 answers

Any function declared or defined as friendinside a class is not a member of this class. This is just a friend function.

, , ADL, ( ).

+10

Pavel - , , , , , , , .

, ( ) . :

class Rectangle
{
...
    friend ostream &operator<<(ostream &stream, Rectangle r);
private:
    int width;
    int height;
};

friend ostream &operator<<(ostream &stream, Rectangle r)
{
    return (stream << "{" << width << ", " << height << "}");
}

friend , get . , , .

+10

.

. CRectangle duplicate (CRectangle);

- , private member. -, .

set_values ​​ , , . . ( ).

CRectangle:: , set_values, CRectangle.

DeusAduro , , - .

+1

, .

, - friend.

. - : . E. g. set_values width height, , set_values .

, width height duplicate(), - , i. . - . , duplicate() CRectangle, , .

Another point: a friend’s declaration is not even a function declaration. For the compiler, just a note: if this particular function is ever defined, it should be granted access to private members of this class.

+1
source

Source: https://habr.com/ru/post/1716744/


All Articles