简体   繁体   中英

A friend function of a class that can only be used by a specific class

I have three different classes A , B , and C . Can I create a function, f , that can access the private members of A and have f callable only by B (and not by C )?

I am looking for an alternative to making class B a friend of class A .

Sure. Make the friend function in question take as an argument class with private constructor of which B is the only friend . Example:

#include <iostream>

class A;
class B;

template <typename T>
class Arg {
    friend T; // only T can make Arg<T>
};

void foo(A& a, Arg<B> );  // only B can make a Arg<B>
                          // so foo is only callable by B

class B {
public:
    void bar(A& a) {       // public for demonstration purposes
        foo(a, Arg<B>{});  // but this can just as easily be private
    }
};

class A {
    friend void foo(A&, Arg<B>);   // foo can access A's internals
    int x;
public:
    void print() { std::cout << x << '\n'; }
};

void foo(A& a, Arg<B> ) { a.x = 42; }

int main() {
    A a;
    B b;
    b.bar(a);
    a.print();
}

foo is a friend of A that can only be used by B .

If you fully-qualify the friend function, then yes, you can restrict. Something like this should allow B but not C.

class A
{
   private:
      int a;
      int b;

  friend int B::accessInternalsViaFriend();
}

class B
{
   .
   .
   .
   public:
      int accessInternalsViaFriend();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM