C++ 中的嵌套命名空间 [英] Nested NameSpaces in C++

查看:32
本文介绍了C++ 中的嵌套命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有嵌套的命名空间和对象声明时,我很困惑该怎么做.

I am confused what to do when having nested namespaces and declarations of objects.

我正在移植一些链接到具有一些命名空间的静态库的代码.

I am porting some code that links against a static library that has a few namespaces.

我所说的例子:

namespace ABC {

    namespace XYZ {

        //STUFF
    }
}

如何在代码中声明一个位于命名空间 XYZ 中的对象?

In code what do I do to declare an object that is in namespace XYZ?

如果我尝试:

XYZ::ClassA myobject;

或:

ABC::XYZ::ClassA myobject;

或:

ABC::ClassA myobject;

我明白了

没有命名类型

错误,即使 ClassA 确实存在.

errors, even though ClassA definitely exists.

这里有什么合适的?

推荐答案

这取决于你已经在的命名空间:

It depends on the namespace you already are:

如果您不在命名空间或另一个不相关的命名空间中,则必须指定整个路径 ABC::XYZ::ClassA.

If you're in no namespace or another, unrelated namespace, then you have to specify to whole path ABC::XYZ::ClassA.

如果您在 ABC 中,则可以跳过 ABC 并直接编写 XYZ::ClassA.

If you're in ABC you can skip the ABC and just write XYZ::ClassA.

另外,值得一提的是,如果你想引用一个不在命名空间(或根"命名空间)中的函数,你可以在它前面加上 :::

Also, worth mentioning that if you want to refer to a function which is not in a namespace (or the "root" namespace), you can prefix it by :::

例子:

int foo() { return 1; }

namespace ABC
{
  double foo() { return 2.0; }

  void bar()
  {
    foo(); //calls the double version
    ::foo(); //calls the int version
  }
}

这篇关于C++ 中的嵌套命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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