friend class with limited access(访问受限的朋友类)
问题描述
我想让 A 类成为 B 类的朋友类.我想这样做,因为这些交互非常频繁,并且 A 需要更改 B 类的内部结构(我不想使用 public 公开).但我想确保它只能访问少数选定的功能,而不是所有功能.
I want to make a class A friend class of class B. I want to do this as these interact very much and A needs to change internals of class B (which I dont want to expose using public). But I want to make sure it has access to only a few selected functions not all the functions.
示例:
class A
{
};
class B
{
private:
void setState();
void setFlags();
friend class A
};
我希望 A 能够访问 setState 但不能访问 setFlags...是否有设计模式或一种很好的方法来做到这一点,或者在这种情况下我是否可以提供完全访问权限或根本没有访问权限.
I want A to be able to access setState but not setFlags... Is there a design pattern or a nice way of doing this or am I left with giving full access or no access at all in this case.
谢谢
推荐答案
这取决于您所说的一种不错的方式"是什么意思:) 在 comp.lang.c++.moderated 之前,我们遇到了同样的问题.你可能会看到它产生的讨论 那里.
It depends on what you mean by "a nice way" :) At comp.lang.c++.moderated we had the same question a while ago. You may see the discussion it generated there.
IIRC,我们最终使用了嵌套键的朋友"方法.应用于您的示例,这将产生:
IIRC, we ended up using the "friend of a nested key" approach. Applied to your example, this would yield:
class A
{
};
class B
{
public:
class Key{
friend class A;
Key();
};
void setFlags(Key){setFlags();}
private:
void setState();
void setFlags();
};
这个想法是公共 setFlags() 必须用Key"调用,只有 Key 的朋友才能创建一个,因为它的 ctor 是私有的.
The idea is that the public setFlags() must be called with a "Key", and only friends of Key can create one, as its ctor is private.
这篇关于访问受限的朋友类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:访问受限的朋友类
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
