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

Definition or redeclaration not allowed inside a function

本文关键字:声明 新声明 内部 不允许 定义 函数      更新时间:2023-10-16

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 }

当试图在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++标准允许您在声明时初始化它们(如在.h文件中),但您仍然必须定义它们,但这次没有初始化器:

const double Something::fudgeFactor;

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