我试图了解using
在命名空间中包含声明会产生什么样的错误。我正在考虑这些 链接。
我正在尝试创建一个示例,其中由于使用using
声明,名称被静默替换为在另一个文件之前加载的头文件而导致错误。
我在这里定义MyProject::vector
:
// base.h
#ifndef BASE_H
#define BASE_H
namespace MyProject
{
class vector {};
}
#endif
这是“坏”的标题:在这里,我试图using
隐藏其他可能的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
这是试图使用的毫无戒心的标头MyProject::vector
,定义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
:
// main.cpp
// If I swap these two, program compiles!
#include "x.h"
#include "z.h"
int main()
{
MyProject::useVector();
}
如果我包含using std::vector
in x.h
,则会发生实际编译错误,告诉我在使用vector
in时必须指定模板参数z.h
,因为x.h
成功地隐藏了vector
inside的定义MyProject
。这是一个很好的例子,说明为什么using
不应该在头文件中使用声明,或者事情比这更深入,我错过了更多?
但是,如果我包含using namespace std
in x.h
,则不会发生阴影,并且程序编译得很好。这是为什么?不应该using namespace std
加载所有可见的名称std
,包括vector
,从而遮蔽另一个?