如何限制类在其声明的命名空间之外的可见性? [英] How to restrict the visibility of a class outside the namespace in which it is declared?

查看:205
本文介绍了如何限制类在其声明的命名空间之外的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++中有一个命名空间,其中包含5个类。所有这些都有 public 访问修饰符。其中,2个类是 static 类。

I have a namespace in c++ which contains 5 classes. All of them are having public access modifier. Out of these, 2 classes are static classes.

我想限制这些类在命名空间外部可见

I want to restrict these classes to be visible outside the namespace in which they are declared.

所以,像另一个命名空间,如果我导入这个命名空间,那么这两个类不应该可用。

So, like in another namespace, if I import this namespace, then these 2 classes should not be available to use.

推荐答案

C ++中没有静态类。如果通过 static classes 表示代码中其他类使用的助手类,而不是被客户端代码使用,那么可以使用未命名的命名空间,并在其中定义助手类。 / p>

There aren't static classes in C++. If by static classes you mean helper classes used by other classes in your code, and are not meant to be used by client code, then you can use unnamed namespace, and define the helper classes inside them.

namespace somespace
{
    namespace   //it is unnamed namespace
    {
           class helper
           {
               //define it here
           };
    }
    class A
    {
          helper m_helper;
    };
}

Boost也使用另一种技术。它在名为 details 的命名空间中定义所有辅助类。

Boost uses another technique as well. It defines all the helper classes in a namepace called details.

namespace somespace
{
    namespace details  //it is details namespace
    {
           class helper
           {
               //define it here
           };
    }
    class A
    {
          details::helper m_helper;  //use fully-qualified name
    };
}

这篇关于如何限制类在其声明的命名空间之外的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆