内部命名空间的C ++命名空间解析

时间:2014-12-02 22:06:49

标签: c++ namespaces using

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

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()
{
}

2 个答案:

答案 0 :(得分:3)

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.

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

免责声明:我实际上并不知道如何正常使用。

答案 1 :(得分:1)

短篇小说:using namespace是访问现有声明的一个很好的快捷方式,但它对后续声明 。 (否则他们显然会完全模棱两可!)

相关问题