允许C++类访问其他类的某些"internal"成员,但不允许访问私有类?

Allow C++ class to access some "internal" member of other class, but not private?

本文关键字:访问 不允许 成员 internal 其他 允许 C++      更新时间:2023-10-16

当对功能紧密耦合的类进行编码时,如果您想要一个与外界的简单接口,那么我可以这样做:

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_privatelog_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"方法。

我非常喜欢这种方法来记录有限的访问