سؤال

What is the real use of a friend function/class in C++? Could you give an example where only friend is the right approach?

Thanks

هل كانت مفيدة؟

المحلول

"In C++, only your friends can access your private parts."

The point of a friend is that you can package your software into smaller groupings, like friend classes etc, while still allowing access to the internals of a class. This arguably lets you maintain finer control on encapsulation than without friending.

نصائح أخرى

i think often friend function usage its a matter of readability. For example next overloaded operator looks symmetrically and this may be good for code reader.

friend const X operator+(const X&, const X&);

inline const X operator+(const X& arg1, const X& arg2)
{
    X r;
    r.x = arg1.x + arg2.x;
    return r;
}

But main point its their ability to access private data of two different classes.

Using friend is actually very discouraged in C++ (it kinda breaks the whole encapsulation idea), but it comes to my mind an example where only friend is the right approach:

friend ostream & operator<< (ostream & out, const MyClass & C);
friend istream & operator>> (istream & in, MyClass & C);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top