函数内部不允许定义或重新声明
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 }
当试图在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;
类的静态数据成员需要有外部链接。根据此规则,静态成员必须在命名空间范围中定义。
相关文章:
- 如何从构造函数声明新的私有变量?
- 使用 basic_string 声明新类型的字符串
- STD :: bad_alloc在声明新的int [n]时
- 了解函数错误的歧义新声明
- 使用模板在类中声明新函数
- 使用括号会在声明新节点时会产生错误
- QT应用程序声明新对象后崩溃
- 新声明在使用delete时包含垃圾值和堆损坏
- 是否有C#中的C 新声明
- 当我想为结构体声明新成员时,有些麻烦我不明白
- 声明新节点但不等于 NULL
- 使用以前的函数参数声明新的函数参数是否合法
- 如何在Qt 5中声明新信号槽语法作为函数参数
- 获取错误:新声明符中的表达式必须具有整型或枚举类型C++
- 在初始化中使用新声明的变量(int x=x+1)
- 如何解决编译器枚举重新声明冲突
- 非ptr新声明符中的错误表达式
- 如何使用c++中的类模板声明新的运算符
- 用C++中现有映射的地址分配新声明的映射的地址可以吗
- 正在声明新的数字类型