C ++ OOP仅授予对某些类的访问权限 [英] C++ OOP Only grant access to certain classes
问题描述
我想实现一个 Container
类,只能按照我想要的类访问,类似于下面的
I would like to implement a Container
class 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;
};
现在我想要访问 Container
数据如下:
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?
推荐答案
你的做法是错误的,因为友谊不是继承的。但是,有一个很好的方法来解决你要解决的问题,这是私人继承。
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();
};
这样你就可以选择任何需要使用的类 class Container
同时您也阻止其他用户使用您的课程。
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.
这篇关于C ++ OOP仅授予对某些类的访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!