如何从嵌套的C++命名空间中引用外部C++命名空间?

Lil*_*ily 5 c++ gcc namespaces

我在默认的"根"命名空间中定义了两个名称空间,nsAnsB. nsA有一个子命名空间nsA :: subA.当我尝试引用属于nsB的函数时,从nsA :: subA内部,我收到一个错误:

undefined reference to `nsA::subA::nsB::theFunctionInNsB(...)'
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

i_a*_*orf 7

使用全局范围解析:

::nsB::TheFunctionInNsB()
Run Code Online (Sandbox Code Playgroud)


Mic*_*urr 5

#include <stdio.h>

namespace nsB {
    void foo() {
        printf( "nsB::foo()\n");
    }
}

namespace nsA {
    void foo() {
        printf( "nsA::foo()\n");
    }

    namespace subA {
        void foo() {
            printf( "nsA::subA::foo()\n");
            printf( "calling nsB::foo()\n");

            ::nsB::foo();      // <---  calling foo() in namespace 'nsB'
        }
    }
}

int main()
{
    nsA::subA::foo();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*sop 2

需要更多信息来解释该错误。下面的代码很好:

#include <iostream>

namespace nsB {
    void foo() { std::cout << "nsB\n";}
}

namespace nsA {
    void foo() { std::cout << "nsA\n";}
    namespace subA {
        void foo() { std::cout << "nsA::subA\n";}
        void bar() {
            nsB::foo();
        }
    }
}

int main() {
    nsA::subA::bar();
}
Run Code Online (Sandbox Code Playgroud)

因此,虽然指定全局命名空间可以解决您当前的问题,但通常可以在没有全局命名空间的情况下引用 nsB 中的符号。否则,每当您处于另一个名称空间范围时,您都必须编写 ::std::cout、::std::string 等。而你却没有。量子ED。

指定全局命名空间适用于当前作用域中存在另一个可见的 nsB 的情况 - 例如,如果 nsA::subA 包含其自己的命名空间或名为 nsB 的类,并且您想要调用 ::nsbB:foo 而不是 nsA::subA: :nsB::foo。因此,如果您已声明(但未定义) nsA::subA::nsB::theFunctionInNsB(...),您会收到引用的错误。您是否可能从命名空间 subA 内 #include nsB 的标头?