允许C++类访问其他类的某些"internal"成员,但不允许访问私有类?
Allow C++ class to access some "internal" member of other class, but not private?
当对功能紧密耦合的类进行编码时,如果您想要一个与外界的简单接口,那么我可以这样做:
class log
{
private:
log_context& cont;
public:
create_log_section(std::string name)
{
cont.create_log_section(name);// this is fine! It's "internal"
cont.this_is_private(); // doesn't compile. Don't want anyone touching my privates!
}
};
class log_context
{
internal:
void create_log_section(std::string name);
private:
void this_is_private();
internal friend log; // Wow, possible?
}
现在,这将允许log访问上下文的相关部分,但不能访问私有部分。程序的其余部分应该使用log来添加任何上下文。它还可以在日志之间传递强类型的log_contexts
,而不需要任何额外的功能。我知道这个特殊的解是不可能的,但是如果有的话,有哪些常见的解呢?
您可以使用一个内部类来完成此操作
class log_context
{
class internal
{
friend log;
static void create_log_section( log_context & context, std::string name)
{
context.create_log_section( name );
}
}
private:
void create_log_section(std::string name);
void this_is_private();
}
class log
{
private:
log_context& cont;
public:
void create_log_section(std::string name)
{
log_context::internal::create_log_section( cont, name );// this is fine! It's "internal"
}
};
作为私有静态函数的内部函数,只有它的友元可以访问
友谊不会跨越继承的界限。如果log_context
继承了一些log_context_base
,而this_is_private
是log_context_base
的一部分,那么log_context
作为log
的朋友,就不会允许log
访问this_is_private
。
class log_context_base
{
protected:
void this_is_private();
}
class log_context : protected log_context_base
{
internal:
void create_log_section(std::string name);
friend log;
}
请注意,我在这里使用了受保护的继承,因为我不希望使用log_context_base*
访问log_context。
这样,您就可以得到您想要的,而不必为语言添加新的关键字;)
一般的解决方案是让full
成为朋友,因为它在你的控制之下,只要确保它只触摸它应该触摸的东西。
我之前提出的另一个解决方案是使用Key
。
class Key { friend class log; Key() {} ~Key() };
class log_context {
public:
void create_log_section(std::string name, Key const&);
};
只有Key的友元可以创建它的实例,因此只有他们(或那些他们传递对Key的引用的人)可以访问"restricted"方法。
我非常喜欢这种方法来记录有限的访问
相关文章:
- 如何确保 Visual C++ 不允许作用域枚举访问?
- 为什么 clang 不允许通过实例访问嵌套枚举类?
- 具有C 的Antlr4中的标签生成不允许访问标签值
- 仅允许访问对象的成员,而不允许访问对象本身
- 方法中不允许访问结构指针
- 不允许转换为无法访问的基类
- 函数从模板参数中获取字段值,而不是直接访问以允许对相同信息使用不同的名称
- 允许按派生类访问,但不允许重写
- C++ 共享库不允许静态数据成员访问
- 是否有技术原因不允许using声明以不同的名称访问函数名
- 从class_Type名称访问矢量值时不允许出现错误
- 重载模板类中的二进制运算符不允许访问私有数据成员
- 为什么标准不允许 std::for_each 对无效的随机访问迭代器范围有明确定义的行为?
- 不允许直接在同一类中访问成员变量
- 为什么不允许我们访问没有公共成员函数的类外私有静态成员?
- Maya c++ API不允许访问某些工具吗?
- xcode 5.1.1抱怨:ISO c++ 11不允许访问声明
- 访问c++类成员对象,但不允许覆盖它
- 允许C++类访问其他类的某些"internal"成员,但不允许访问私有类?
- C++ 为什么对象的副本不允许访问原始对象的私有变量?