【问题标题】:Why redeclaration of a static member is denied为什么拒绝重新声明静态成员
【发布时间】:2014-05-13 07:31:36
【问题描述】:

我认为我们可以在任何情况下随时重新声明一个名称。但是

class A 
{
    static int a;
    static int a;
};

返回编译时错误:

test.cpp:4:13: error: redeclaration of ‘int A::a’
test.cpp:3:13: note: previous declaration ‘int A::a’

实际上可以重新声明哪些名称?

【问题讨论】:

  • 这不是几分钟前在您之前的问题中回答的吗?
  • 如何区分第一个和第二个a
  • @Raxvan 我对这个重新声明在标准中被拒绝的地方感兴趣。你能回答我吗?
  • @deviantfan 这是两个不同的问题。
  • @St.Antario:不是真的,只是相反,应该得到相同的答案。见 Mike Seymours 评论:stackoverflow.com/questions/23624844/…

标签: c++ declaration static-members


【解决方案1】:

根据 C++ 标准(9.2 类成员,第 #1 段)

一个成员不得在成员规范中声明两次, 除了可以声明嵌套类或成员类模板 然后再定义,除了枚举可以是 用不透明枚举声明引入,后来用 一个枚举说明符。

【讨论】:

    【解决方案2】:

    C++11 9.2/1 [class.mem]

    一个成员在member-specification中不能被声明两次,除非可以声明一个嵌套类或成员类模板,然后再定义,除非一个枚举可以用一个opaque-enum-declaration,然后用 enum-specifier 重新声明。

    【讨论】:

    • 谢谢。这就是我要找的。​​span>
    【解决方案3】:

    除了其他答案之外,您的代码不仅是重新声明,而且是重新定义,这显然违反了单定义规则。

    【讨论】:

    • 没有任何重新定义。其实declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification 25 (7.5) and neither an initializer nor a function-body, it declares a static data member in a class definition (9.2, 9.4)
    • 更多详情请参见3.1.2部分
    • 你是对的。我读得太快了,错过了你定义一个类而不是一个函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多