【问题标题】:Member-declaration of C++ Standard GrammarC++ 标准语法的成员声明
【发布时间】:2014-05-24 01:22:52
【问题描述】:

在C++规范的语法中,类的成员是这样定义的:

member-declaration:
  decl-specifier-seq(optional) member-declarator-list(optional);
  function-definition ;(optional)
  ::(optional) nested-name-specifier template(optional) unqualified-id ;//what is this?
  using-declaration
  template-declaration
  ...

我了解其中的 4 个。但是第三个定义了一个强制性的嵌套名称说明符,后跟一个 id。例如

class {
  X::Y::z;
}

我不知道任何符合此定义的 C++ 语法。我错过了什么吗?

【问题讨论】:

  • 不,应该属于第一行:decl-specifier-seq + member-declarator-list 是定义成员变量的方式。
  • 此外,nested-name-specifier 匹配由 :: 终止的内容,例如X:: 所以它不能匹配 X::Y z。它只匹配 X::Y:: 而 z 是不合格的 id
  • 我很想 -1 因为这取决于 C++ 标准的 版本 - 或者,换句话说,这个语法规则不会出现在 C++ 标准,目前是 C++11。您指的是一些较早的草案或以前的标准,而问题中缺少这条信息。

标签: c++ grammar c++03


【解决方案1】:

可以在 [class.access.dcl] 部分找到答案。简而言之,这样的声明称为“访问声明”,其目的是更改继承成员的访问级别。

例如:

class A
{
protected:
    int a;
    int a1;
};

class B
{
public:
    int b;
    int b1;
};

class C : public A, private B
{
public:
    A::a;
    B::b;
}

int f()
{
    C c;

    c.a1; // access error: A::a1 is protected
    c.b1; // access error: B is private base of A

    c.a; // accessible because A::a is 'published' by C
    c.b; // accessible because B::b is 'published' by C
}

这种声明已被using 取代,但出于兼容性目的而保留。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2012-06-22
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多