简体   繁体   English

我可以在 C++ 类中声明“使用命名空间”吗?

[英]May I declare “using namespace” inside a C++ class?

Assume having a C++ class.假设有一个 C++ 类。 And there's a namespace which should be visible only inside my class.并且有一个命名空间应该只在我的类中可见。 What to do for that?为此该怎么办?

class SomeClass
{
    using namespace SomeSpace;

public:
    void Method1();
    void Method2();
    void Method3();
};

namespace SomeSpace
{
    /*some code*/
};

using namespace X; is called a using directive and it can appear only in namespace and function scope, but not class scope.被称为using 指令,它只能出现在命名空间和函数范围内,而不能出现在类范围内。 So what you're trying to do is not possible in C++.所以你想要做的在 C++ 中是不可能的。 The best you could do is write the using directive in the scope of the namespace of that class, which may not be desirable.您能做的最好的事情是在该类的命名空间范围内编写 using 指令,这可能是不可取的。

On second thought, though, analyzing your words,不过,仔细想想,分析你的话,

Assume having a C++ class.假设有一个 C++ 类。 And there's a namespace which should be visible only inside my class.并且有一个命名空间应该只在我的类中可见。 What to do for that?为此该怎么办?

I'd suggest something like the following, which I am not sure is what you want.我建议类似以下内容,我不确定这是您想要的。

class A
{
public:
    void Method1();
    void Method2();
    void Method3();

private:

    class B
    {
       //public static functions here, instead of namespace-scope
       // freestanding functions.
       //these functions will be accessible from class A(and its friends, if any) 
       //because B is private to A
    };

};

No but you can do it like that:不,但你可以这样做:

namespace SomeSpace
{
    /*some code*/
};

using namespace SomeSpace;

class SomeClass
{

public:
    void Method1();
    void Method2();
    void Method3();
};

Though it is not recommended either to apply the using namespace directive in header files and often considered as a bad style.虽然不建议在头文件中应用 using 命名空间指令,但通常被认为是一种糟糕的风格。 It is OK to put in in a source file (.cpp) of your class.可以放入你的类的源文件 (.cpp)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM