Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

C++ Friends of Classes #249

Open Qingquan-Li opened 1 year ago

Qingquan-Li commented 1 year ago

Concept: A friend is a function or class that is not a member of a class, but has access to the private members of the class.

// A friend function as a stand-alone function.

class MyClass
{
private:
    int x;
    friend void fSet(MyClass &c, int a);
};

void fSet(MyClass &c, int a)
{
    c.x = a;
}
// A friend function as a member of another class.
class MyClass
{
private:
    int x;
    friend void OtherClass::fSet(myClass &c, int a);
};

class OtherClass
{
public:
    void fSet(myClass &c, int a)
    {
        c.x = a;
    }
}
// An entire class can be declared a friend of a class.

class MyClass
{
private:
    int x;
    friend class FriendClass;
};

class FriendClass
{
public:
    void fSet(MyClass &c, int a)
    {
        c.x = a;
    }
    int fGet(MyClass c)
    {
        return c.x;
    }
};

If FriendClass is a friend of MyClass, then all member functions of FriendClass have unrestricted access to all private members of MyClass.

In general, you should restrict the property of Friendship to only those functions that must have access to the private members of a class.