1

我试图了解using在命名空间中包含声明会产生什么样的错误。我正在考虑这些 链接

我正在尝试创建一个示例,其中由于使用using声明,名称被静默替换为在另一个文件之前加载的头文件而导致错误。

我在这里定义MyProject::vector

// base.h
#ifndef BASE_H
#define BASE_H

namespace MyProject
{
    class vector {};
}

#endif

这是“坏”的标题:在这里,我试图using隐藏其他可能的vectorinside定义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.hz.h

// main.cpp
// If I swap these two, program compiles!
#include "x.h"
#include "z.h"

int main()
{
    MyProject::useVector();
}

如果我包含using std::vectorin x.h,则会发生实际编译错误,告诉我在使用vectorin时必须指定模板参数z.h,因为x.h成功地隐藏了vectorinside的定义MyProject。这是一个很好的例子,说明为什么using不应该在头文件中使用声明,或者事情比这更深入,我错过了更多?

但是,如果我包含using namespace stdin x.h,则不会发生阴影,并且程序编译得很好。这是为什么?不应该using namespace std加载所有可见的名称std,包括vector,从而遮蔽另一个?

4

1 回答 1

1

但是,如果我在 xh 中包含 using namespace std,则不会发生阴影,并且程序编译得很好。这是为什么?

我可以从 7.3.4/2-3 回答这么多:

第一的

using-directive 指定指定命名空间中的名称可以在 using-directive 出现在 using-directive 之后的范围内使用。

然后跟进:

using 指令不会将任何成员添加到它出现的声明区域。

因此 using-directive ( using namespace) 仅使名称可从目标名称空间中使用,而不会使它们成为目标名称空间的成员。因此,任何现有成员都将优先于使用的命名空间成员。

于 2016-10-03T14:22:16.993 回答