close

轉錄至https://coherence0815.wordpress.com/2015/04/19/static-class-member-initialization-in-c/

在初始化Static class member的時候有一些需要注意的地方,打字猴在這裡做個紀錄。

首先,static class member一定要做初始化:

1
2
3
4
5
6
7
8
9
10
11
12
class CFoo {
public:
    CFoo() {}
    int GetData() { return s_data; }
private:
    static int s_data;
};
 
void main() {
    CFoo foo;
    cout << foo.GetData() << endl;
}

以上程式會出現以下link error:
error LNK2001: unresolved external symbol “private: static int CFoo::s_data” (?s_data@CFoo@@0HA)

1. Static class member無法透過以下方式做initialization

1
2
3
4
5
6
7
class CFoo {
public:
    CFoo() : m_b(15) {}
private:
    static int m_a = 15;
    static int m_b;
};

編譯以上程式會出現以下Compile Error:
error C2864: ‘CFoo::m_a’ : a static data member with an in-class initializer must have non-volatile const integral type
error C2438: ‘m_b’ : cannot initialize static class data via constructor

2. const static class member如果是integral type,就可以in-place的做initialization,不是的話就不行。

1
2
3
4
class CFoo {
private:
    static const int m_a = 15;
};
1
2
3
4
5
6
7
8
#include <iostream>
#include <string>
using namespace std;
 
class CFoo {
private:
    static const string m_str = "Bar";
};

編譯以上程式會出現以下Compile Error:
error C2864: ‘CFoo::m_str’ : a static data member with an in-class initializer must have non-volatile const integral type

3. static class member必須在class裡面宣告,然後在class外定義

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;
 
class CFoo {
private:
    static int m_data;
    static const string m_str;
};
 
int CFoo::m_data = 15;
const string CFoo::m_str = "Bar";

4. 記得不要把static class member定義在header file,以免在多個cpp file都include該header file時,因違反ODR而造成link error。

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 LiLun 的頭像
    LiLun

    LiLun の 分享平台

    LiLun 發表在 痞客邦 留言(0) 人氣()