【问题标题】:C++ namespace resolution for inner namespace内部命名空间的 C++ 命名空间解析
【发布时间】:2014-12-02 22:06:49
【问题描述】:

请解释一下为什么这段代码会导致链接错误:

xxx.h

namespace ns
{
    namespace inner
    {
        void func();
    }
}

xxx.cpp

using namespace ns;
using namespace inner; //or "using "namespace ns::inner;" results in the same error

void func()
{
}

虽然这段代码运行良好:

xxx.h

namespace ns
{
    void func();
}

xxx.cpp

using namespace ns;

void func()
{
}

【问题讨论】:

  • 尝试在xxx.cpp中添加using ns::inner::func;而不是using namespace inner;
  • 如果第二个确实有效,我会感到非常惊讶。
  • 传统上,一个人发布关于哪个人正在询问的错误消息。

标签: c++ namespaces using


【解决方案1】:

using namespace ... 只允许在没有命名空间前缀的情况下引用该命名空间内的名称。您在源代码中定义的任何符号仍将定义在它们当前所在的任何命名空间块中。

要添加该函数的定义,您需要位于内部命名空间内:

// xxx.cpp

using namespace ns::inner;
// we are still outside of the namespace, but we can reference names inside.

namespace ns { namespace inner {
    // now we can define things inside ns::inner
    void func() {

    }
}

// now we are at the global level again.

我猜您通过将其移动到外部命名空间并没有收到链接器错误,因为您的代码没有引用它并且它被排除在链接阶段之外。

免责声明:我实际上并不知道 using 是如何工作的。

【讨论】:

  • "要添加该函数的定义,您需要在内部命名空间内:" 使用限定名称编写定义,例如void ns::inner::func() { },如果定义与先前的声明不匹配,则会给出一个有用的错误。
【解决方案2】:

简短的故事:using namespace 是访问现有声明的一个不错的快捷方式,但它对后续声明没有任何作用。 (否则它们显然会完全模棱两可!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2010-11-08
    • 2010-12-23
    • 2011-09-20
    • 2012-10-14
    • 1970-01-01
    相关资源
    最近更新 更多