【问题标题】:In what scopes is the "using namespace" clause valid? [duplicate]“使用命名空间”子句在什么范围内有效? [复制]
【发布时间】:2020-04-06 08:29:24
【问题描述】:

我曾经听过/读到(参考已经忘记了;无法引用)“using namespace”子句在任何范围内都有效,但在类范围内似乎无效:

// main.cpp

#include <iostream>

namespace foo
{
  void func() { std::cout << __FUNCTION__ << std::endl; }
};

class Foo
{
using namespace foo;

  public:
    Foo() { func(); }
};

int main( int argc, char* argv[] )
{
  Foo f;
}

.

$ g++ --version
g++ (GCC) 8.3.1 20190223 (Red Hat 8.3.1-2)
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

.

$ g++ -g ./main.cpp 
./main.cpp:12:7: error: expected nested-name-specifier before 'namespace'
 using namespace foo;
       ^~~~~~~~~
./main.cpp: In constructor 'Foo::Foo()':
./main.cpp:15:13: error: 'func' was not declared in this scope
     Foo() { func(); }
             ^~~~
./main.cpp:15:13: note: suggested alternative:
./main.cpp:7:8: note:   'foo::func'
   void func() { std::cout << __FUNCTION__ << std::endl; }
        ^~~~
$
$ g++ --std=c++11 -g ./main.cpp 
./main.cpp:12:7: error: expected nested-name-specifier before 'namespace'
 using namespace foo;
       ^~~~~~~~~
./main.cpp: In constructor 'Foo::Foo()':
./main.cpp:15:13: error: 'func' was not declared in this scope
     Foo() { func(); }
             ^~~~
./main.cpp:15:13: note: suggested alternative:
./main.cpp:7:8: note:   'foo::func'
   void func() { std::cout << __FUNCTION__ << std::endl; }
        ^~~~

class Foo 的以下变体导致相同的编译器错误:

class Foo
{
using namespace ::foo;

  public:
    Foo()
    {
      func();
    }
};

class Foo 的以下变体不会导致编译器错误或警告:

class Foo
{
  public:
    Foo()
    {
      using namespace foo;
      func();
    }
};

.

class Foo
{
  public:
    Foo()
    {
      foo::func();
    }
};

基于阅读this 和this 之类的帖子,我(不正确?)对编译器错误的理解是该错误本质上需要对使用的命名空间进行完整的范围界定,即我在第一个变体中尝试@ 987654332@,以上。

请注意:除了显式使用 --std=c++11 编译器标志外,使用的编译器版本远高于不会遇到此错误所需的最低版本(不显式使用 --std=c++11 编译器标志),根据注意到堆栈溢出问答。

这个编译器错误是什么意思(如果与我上述的理解不同)在这种情况下?(我的用法似乎与上面提到的两个 Stack Overflow 不同问答)。

一般来说:“使用命名空间”指令在什么范围内有效?

【问题讨论】:

    标签: c++ compiler-errors namespaces using using-directives


    【解决方案1】:

    来自cppreference.com:

    仅在命名空间范围和块范围内允许使用指令。

    因此您可以在命名空间(包括全局命名空间)或代码块中使用它们。类声明两者都不是。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 2021-10-24
      • 2011-06-28
      • 2013-09-25
      • 2016-01-03
      • 2012-07-28
      相关资源
      最近更新 更多