【问题标题】:Example of error caused by using directive in namespaces在命名空间中使用指令导致的错误示例
【发布时间】:2017-02-09 12:36:00
【问题描述】:

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

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

我在这里定义MyProject::vector

// base.h
#ifndef BASE_H
#define BASE_H

namespace MyProject
{
    class vector {};
}

#endif

这是“坏”标头:在这里,我试图欺骗 usingvector 的其他可能定义隐藏在 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();
}

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

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

【问题讨论】:

    标签: c++ compiler-errors namespaces using-directives using-declaration


    【解决方案1】:

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

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

    第一

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

    然后跟进:

    using-directive 不会向声明区域添加任何成员 它出现在其中。

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

    【讨论】:

    • 谢谢!我不知道using 的两种用法之间的区别。
    猜你喜欢
    • 1970-01-01
    • 2011-07-01
    • 2012-01-10
    • 2011-01-02
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    相关资源
    最近更新 更多