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

2019-07-23 03:30发布

This question already has an answer here:

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?

标签: c++ oop
2条回答
Viruses.
2楼-- · 2019-07-23 04:21

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.

查看更多
劫难
3楼-- · 2019-07-23 04:32

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.

查看更多
登录 后发表回答