2013-11-26 101 views
0

在一個類Foo中我有枚舉OperatorsTypes。和方法,用於初始化與枚舉assutiatied值 :初始化與枚舉關聯的值的最佳方法是什麼?

void InitializeOpTypesCC() 
{ 
    _operatorTypeContactCount[OperatorsTypes::CreateChannel] = 3; 
    _operatorTypeContactCount[OperatorsTypes::CreateOperator] = 1; 
    _operatorTypeContactCount[OperatorsTypes::DeleteChannel] = 2; 
    _operatorTypeContactCount[OperatorsTypes::Division] = 2; 
    _operatorTypeContactCount[OperatorsTypes::Equal] = 1; 
    _operatorTypeContactCount[OperatorsTypes::GetOperatorContactsCount] = 1; 
    _operatorTypeContactCount[OperatorsTypes::GetInputOperatorId] = 1; 
    _operatorTypeContactCount[OperatorsTypes::GetTypeOfOperator] = 1; 
    _operatorTypeContactCount[OperatorsTypes::If] = 2; 
    _operatorTypeContactCount[OperatorsTypes::IsChannelExists] = 3; 
    _operatorTypeContactCount[OperatorsTypes::Minus] = 2; 
    _operatorTypeContactCount[OperatorsTypes::Multiplication] = 2; 
    _operatorTypeContactCount[OperatorsTypes::One] = 0; 
    _operatorTypeContactCount[OperatorsTypes::Plus] = 2; 
    _operatorTypeContactCount[OperatorsTypes::RandomNumber] = 1; 
    _operatorTypeContactCount[OperatorsTypes::RemoveOperator] = 1; 
    _operatorTypeContactCount[OperatorsTypes::Time] = 0; 
    _operatorTypeContactCount[OperatorsTypes::Nothing] = 0; 
} 

Curently我打電話從構造此方法。但我從方法構造方面來看簡直就是一般時機。所以我想使這個 初始化和_operatorTypeContactCount靜態。不爲所有實例啓動它。 我用靜態標記了InitializeOpTypesCC和_operatorTypeContactCount,並開始得到 鏈接錯誤。我讀到了這個靜態限制。然後我將_operatorTypeContactCount和InitializeOpTypesCC移動到命名空間範圍並將其標記爲靜態。這工作,但我需要manualy調用InitializeOpTypesCC並得到未定義的行爲,當我忘記了,例如在單元測試。這種情況下最好的方法是什麼?

這可以是常量靜態數組,但我需要通過索引以初始化它,如: const int的測試[] = { [IND1] = 10, [IND2] = 5, //。 //。 //。 } ;.在const char Foo :: array [] = {'1','2','3'}中不是一個接一個的。這是不方便的,因爲枚舉可以改變。

+0

http://stackoverflow.com/q/18784796/1175253 – Sam

+0

靜態類成員+鏈接器錯誤:它看起來像只在h文件中將此成員聲明爲靜態並且未在.cpp文件中創建變量。 –

+0

爲什麼你認爲初始化18個變量需要花費大量的時間? –

回答

1
DependentType 
{ 
    static bool staticInit = false; 

    //**NOT** thread safe!! (you'd need a static sync primitive) 
    if(!staticInit) 
    { 
     staticInit = true; 
     DoStaticInit(); 
    } 
} 

或全局:

bool StaticInit() 
{ 
    static bool staticInit = false; 

    //**NOT** thread safe!! (you'd need a static sync primitive) 
    if(!staticInit) 
    { 
     staticInit = true; 
     DoStaticInit(); 
     return true; 
    } 
    return false; 
} 

DependentType() 
{ 
    //Add this to all dependent type's constructor or class body 
    static const bool staticInit = StaticInit(); 
} 

即使您運行從另一個靜態初始化靜態初始化,只要你有DependentType靜態實例,這取決於靜態初始化順序,這是很難預測甚至更難維護。

另一種方式是使用迭代器和任何需要的適配器類來包裝靜態數組:
Link two enumated type members

+0

謝謝。但是這個檢查會有一些開銷......我認爲使用靜態成員,一些類,Zoo以及_operatorTypeContactCount數組初始化,會更好。 –

相關問題