2013-10-03 134 views
1

我該如何初始化一個靜態成員變量「動態」?如何初始化一個靜態成員變量「動態」?

舉例來說,我宣佈在類的頭文件,這個變量:

class MyPermutation { 
    static std::array<std::vector<uint8_t>,2> permutation_list; 
}; 

而且我希望它有以下值:

permutation_list[0] = std::vector<uint8_t>{0}; 
permutation_list[1] = std::vector<uint8_t>{}; 
for (uint8_t i = 0; i < 8; i++) 
    permutation_list[1].push_back(1<<i); 

我應該在哪裏把上面的代碼?

+1

也許能幫助:http://stackoverflow.com/questions/1197106/static-constructors-in-c-need-to-initialize-private-static-objects – codeling

回答

3

這通常是由一個被稱爲初始化靜態變量函數來完成:

std::array<std::vector<uint8_t>,2> MyPermutation::permutation_list = someFunctionThatBuildsTheInitialValues(); 

或者,因爲C++ 11,它可以是一個lambda:

std::array<std::vector<uint8_t>,2> MyPermutation::permutation_list = 
    []() -> std::array<std::vector<uint8_t>,2> { 
    std::array<std::vector<uint8_t>,2> the_list; 
    the_list[0] = std::vector<uint8_t>{0}; 
    the_list[1] = std::vector<uint8_t>{}; 
    for (uint8_t i = 0; i < 8; i++) 
     the_list[1].push_back(1<<i); 
    /* ... */ 
    return the_list; 
    }();