【发布时间】: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