函数内不允许定义或重新声明

Definition or redeclaration not allowed inside a function

Something.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 }

当试图定义 Class Something inside main 的静态成员变量的值时,我遇到了一个编译器错误,如下所示。在 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++ 标准允许您在声明时初始化它们(如在您的 .h 文件中),但您仍然必须定义它们,但这次没有初始化器:

const double Something::fudgeFactor;

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