c++ - “使用命名空间”子句在什么范围内有效?
问题描述
我曾经听过/读过(参考已经滑倒了我的脑海;无法引用它)“ 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之类的帖子,该错误本质上需要对使用的命名空间进行完整范围界定,即我在class Foo
上面的第一个变体中尝试的内容。
请注意:根据 Stack Overflow Q&A 的说明,除了显式使用--std=c++11
编译器标志外,使用的编译器版本远高于不会遇到此错误的最低要求(没有显式使用编译器标志)。--std=c++11
在这种情况下,这个编译器错误是什么意思(如果与我的上述理解不同)?(我的用法与前面提到的两个 Stack Overflow Q&A 中的用法不同)。
一般来说:“使用命名空间”指令在什么范围内有效?
解决方案
推荐阅读
- html - 响应式侧边栏上下滚动
- javascript - ModuleParseError:模块解析失败:意外字符“�”
- android - Tensorflow Lite 输入字符串
- windows - 调用 vcvarsall.bat 在 Windows 7 / VS 2019 构建工具上给出“Windows 找不到 powershell.exe”
- java - Sonar hostpot:放置向导中的主要应用
- node.js - 在 nodejs 服务器中处理绝对 url
- vue.js - 如何在生产版本的 Vue 项目中使 fontawesome 工作?
- mongodb - 查找具有与 mongodb 中的条件匹配的数组项的文档
- c++ - 特征:自动/符号微分
- plugins - 插件在我们可以连接之前退出