问题描述
我试图了解在名称空间中包含using
声明会引起什么样的错误.我考虑了这些 链接.
I'm trying to understand what kind of errors could arise from including using
declarations in namespaces. I'm taking into account these links.
我正在尝试创建一个示例,其中由于使用using
声明而导致一个错误,该错误是由于将一个名称静默替换为在另一个文件之前加载的头文件而引起的.
I'm trying to create an example where an error is being caused by a name being silently replaced by an header file being loaded before another one, due to usage of the using
declaration.
这里我要定义MyProject::vector
:
// base.h
#ifndef BASE_H
#define BASE_H
namespace MyProject
{
class vector {};
}
#endif
这是坏"标题:在这里,我试图欺骗using
使其掩盖MyNamespace
中vector
的其他可能定义:
This is the "bad" header: here I'm trying to trick using
into shadowing other possible definitions of vector
inside MyNamespace
:
// x.h
#ifndef X_H
#define X_H
#include <vector>
namespace MyProject
{
// With this everything compiles with no error!
//using namespace std;
// With this compilation breaks!
using std::vector;
}
#endif
这是毫无疑问的标题,试图使用base.h
中定义的MyProject::vector
:
This is the unsuspecting header trying to use MyProject::vector
as defined in base.h
:
// z.h
#ifndef Z_H
#define Z_H
#include "base.h"
namespace MyProject
{
void useVector()
{
const vector v;
}
}
#endif
最后是实现文件,包括x.h
和z.h
:
And finally here's the implementation file, including both x.h
and z.h
:
// main.cpp
// If I swap these two, program compiles!
#include "x.h"
#include "z.h"
int main()
{
MyProject::useVector();
}
如果在x.h
中包含using std::vector
,则会发生实际的编译错误,并告诉我在z.h
中使用vector
时必须指定模板参数,因为x.h
成功地使阴影的定义变得模糊不清. MyProject
内部的vector
.这是一个很好的示例,说明为什么不应该在头文件中使用using
声明,或者为什么更深层的声明,而我却遗漏了更多内容?
If I include using std::vector
in x.h
, an actual compilation error happens, telling me that I must specify a template argument when using vector
in z.h
, because x.h
successfully managed to shadow the definition of vector
inside MyProject
. Is this a good example of why using
declarations shouldn't be used in header files, or things go deeper that this, and I'm missing much more?
但是,如果我在x.h
中包含using namespace std
,则不会发生阴影,并且程序可以正常编译.这是为什么? using namespace std
是否不应该加载在std
下可见的所有名称,包括vector
,从而遮盖另一个名称?
If I include using namespace std
in x.h
, however, the shadowing doesn't occur, and the program compiles just fine. Why is that? Shouldn't using namespace std
load all names visible under std
, including vector
, thus shadowing the other one?
推荐答案
我可以从7.3.4/2-3中回答以下内容:
This much I can answer from 7.3.4/2-3:
第一
然后跟进:
因此,使用指令(using namespace
)仅使名称可从目标名称空间使用,而不会使其成为其成员.因此,任何现有成员都将优先于使用的名称空间成员.
So a using-directive (using namespace
) only makes the names usable from the target namespace, it does not make them members of it. So any existing member will be preferred over the used namespace member.
这篇关于在命名空间中使用指令导致的错误示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!