【问题标题】:How do I reference an external C++ namespace from within a nested one?如何从嵌套命名空间中引用外部 C++ 命名空间?
【发布时间】:2009-04-29 17:50:56
【问题描述】:

我在默认/“根”命名空间中定义了两个命名空间,nsAnsBnsA 有一个子命名空间 nsA::subA。当我尝试从 nsA::subA 内部引用属于 nsB 的函数时,出现错误:

undefined reference to `nsA::subA::nsB::theFunctionInNsB(...)'

有什么想法吗?

【问题讨论】:

    标签: c++ gcc namespaces


    【解决方案1】:

    使用全局范围解析:

    ::nsB::TheFunctionInNsB()
    

    【讨论】:

      【解决方案2】:
      #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;
      }
      

      【讨论】:

        【解决方案3】:

        需要更多信息来解释该错误。下面的代码就可以了:

        #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();
        }
        

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

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

        【讨论】:

        • "您是否可能从命名空间 subA 中 #include nsB 的标头?" ——确实,我有。很好的收获,很好的解释。
        猜你喜欢
        • 2015-01-08
        • 2021-12-23
        • 2011-01-02
        • 2019-08-03
        • 1970-01-01
        • 2011-03-13
        • 1970-01-01
        • 2011-01-06
        • 1970-01-01
        相关资源
        最近更新 更多