【问题标题】:Definition or redeclaration not allowed inside a function [duplicate]函数内部不允许定义或重新声明[重复]
【发布时间】:2015-11-12 22:14:34
【问题描述】:

某事.h

  1 class Something
  2 {
  3 private:
  4     static int s_nIDGenerator;
  5     int m_nID;
  6     static const double fudgeFactor;    // declaration - initializing here will be warning
  7 public:
  8     Something() { m_nID = s_nIDGenerator++; }
  9 
 10     int GetID() const { return m_nID; }
 11 };

foo.cpp

  1 #include <iostream>
  2 #include "Something.h"
  3 
  4 // This works!
  5 //const double Something::fudgeFactor = 1.57;
  6 
  7 int main()
  8 {
  9     Something cFirst;
 10     Something cSecond;
 11     Something cThird;
 12 
 13     const double Something::fudgeFactor = 3.14;
 14 
 15     using namespace std;
 16     cout << cFirst.GetID() << endl;
 17     cout << cSecond.GetID() << endl;
 18     cout << cThird.GetID() << endl;
 19     return 0;
 20 }

当试图在 main 中定义 Class Something 的静态成员变量的值时,我遇到了如下所示的编译器错误。在 main() 之外分配一个值可以正常工作。我知道静态成员变量只能被赋予一次值,但是为什么在函数外部而不是在函数内部赋值呢?

$ clang++ foo.cpp foo.cpp:13:29: error: definition or redeclaration of 'fudgeFactor' not allowed inside a function const double Something::fudgeFactor = 3.14; ~~~~~~~~~~~^ 1 error generated.

【问题讨论】:

    标签: c++ static-members


    【解决方案1】:

    您没有分配函数内部的变量;您正在定义它(并初始化它)。由于范围规则,您不能在函数内部执行此操作。该变量在全局(命名空间)范围内声明;因此它也必须在命名空间范围内定义。它不是局部变量。

    顺便说一句,对于静态 const 变量,最近的 C++ 标准允许您在声明时初始化它们(如在 .h 文件中),但您仍然必须定义它们,但这次没有初始化器:

    const double Something::fudgeFactor;
    

    【讨论】:

    • 你可以,你必须使用constexpr而不是const
    • 是的,你是对的。实际上,我正在考虑删除此答案,因为您的评论非常正确地指出该问题是重复的,我们不想用重复来污染 SO。
    【解决方案2】:

    类的静态数据成员需要有外部链接。根据这条规则,静态成员必须定义在命名空间范围内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-15
      • 2011-11-24
      • 1970-01-01
      • 2012-04-14
      • 2020-10-20
      • 1970-01-01
      • 2013-01-05
      相关资源
      最近更新 更多