C++ OOP Only grant access to certain classes [dupl

2019-07-23 03:49发布

问题:

This question already has an answer here:

  • Why does C++ not allow inherited friendship? 10 answers

I would like to implement a Containerclass that can only be accessed by the classes I want, in a way similar to the following

class ContainerAccess {
    // empty 
};

class Container{
  private:
    static void _do_stuff();
    static int _value;

    friend class ContainerAccess;
};

Now I want to have access to the Container data as follows:

class Processor: public ContainerAccess {
  public:
    void proccess() {
      Container::_do_stuff();
      Container::_value++;
    }
};

However, this does not work. Why is that? And how could that be done?

回答1:

Your approach is wrong as friendship is not inherited. However, there is a good way to solve what you are trying to solve and that's private inheritance.

class Container
{
  protected:
    static void _do_stuff();
    static int _value;
};


class ContainerAccess : private Container 
{
    //using _do_stuff();
};

This way you can chose whatever classes need to use class Container at the same time you also prevent other users from using your class.



回答2:

A possible alternative would be to not make the methods of Container private static, but instead make them only public.

Then, in your main function, create a single instance of Container, and pass it around to methods/classes who need access to the functionality provided by Container.

class Processor {
  public:
    void process(Container & container) {
      container.do_stuff();
      container.value++;
    }
};

The methods who you do not give an instance of Container cannot then operate.



标签: c++ oop