类或使用声明的枚举

Class or enumeration using declaration

本文关键字:枚举 声明      更新时间:2023-10-16

N3797的3.4.3.1/1开头说:

如果限定id的嵌套名称说明符指定了一个类,则类中查找嵌套名称说明符后指定的名称类的范围(10.2),但下列情况除外。

,其中一条规则是:

查找using声明(7.3.3)中指定的名称查找隐藏在同一作用域中的类名或枚举名(3.3.10)。

你能举个例子来说明这个规则吗?

我相信这就是标准所规定的:

struct A {
  struct s {} s;
  enum e { e };
};
struct B: A {
  using A::s;
  using A::e;
};
struct B::s s2;
enum B::e e2;

B作用域中的using-declarations将类名A::s和枚举名A::e带入作用域,尽管它们分别由成员和枚举数隐藏。

注意using声明s也将成员和枚举数带入作用域,因此类和枚举仍然隐藏在B的作用域中;这意味着要在B或其他地方使用它们,我们需要使用structenum标签。

在以下代码中,B::m_sA::m_s隐藏在C中。但它可以通过using A::m_s直接访问。

注释掉using指令。

#include <iostream>
#include <string>
struct A {
    std::string m_s;
    A() :
        m_s("I am A::m_s")
    {}
};
struct B: A {
    std::string m_s;
    B() :
        m_s("I am B::m_s")
    {}
};
struct C: B {
    using A::m_s;

};
int main() {
    C c;
    std::cout << 'n' << c.C::m_s << 'n';
}
/*
    Local Variables:
    compile-command: "g++ -g test.cc -o a.exe && ./a.exe"
    End:
 */