【发布时间】:2017-02-09 12:36:00
【问题描述】:
我试图了解在命名空间中包含 using 声明可能会产生什么样的错误。我正在考虑theselinks。
我正在尝试创建一个示例,其中由于使用了 using 声明,名称被静默替换为在另一个文件之前加载的头文件,从而导致错误。
我在这里定义MyProject::vector:
// base.h
#ifndef BASE_H
#define BASE_H
namespace MyProject
{
class vector {};
}
#endif
这是“坏”标头:在这里,我试图欺骗 using 将 vector 的其他可能定义隐藏在 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();
}
如果我在x.h 中包含using std::vector,则会发生实际编译错误,告诉我在z.h 中使用vector 时必须指定模板参数,因为x.h 成功地隐藏了vector 内 MyProject。这是为什么 using 声明不应该在头文件中使用的一个很好的例子,或者事情比这更深入,我错过了更多?
如果我在x.h 中包含using namespace std,则不会出现阴影,并且程序编译得很好。这是为什么? using namespace std 不应该加载所有在std 下可见的名称,包括vector,从而遮蔽另一个?
【问题讨论】:
标签: c++ compiler-errors namespaces using-directives using-declaration