Where would you use a friend function vs. a static member function?

后端 未结 15 2205
[愿得一人]
[愿得一人] 2020-12-02 04:56

We make a non-member function a friend of a class when we want it to access that class\'s private members. This gives it the same access rights as a static member function w

15条回答
  •  北海茫月
    2020-12-02 05:30

    Static function can only access members of one class. Friend function has access to several classes, as explained by the following code:

    class B;
    class A { int a; friend void f(A &a, B &b); };
    class B { int b; friend void f(A &a, B &b); };
    void f(A &a, B &b) { std::cout << a.a << b.b; }
    

    f() can access data of both A and B class.

提交回复
热议问题