2016-10-04 58 views
2

我有一個計時器類,裏面有一個標誌。當我們沒有調用的init(),標記爲0後,我們調用的init(),它將我們所說的端部(後置爲1),它將被重新設置爲0。如何正確設置標誌

class TimerHao 
{ 
private: 
    double seconds; 
    int flag=0; //0: Have not start accumulation. 1: In accumulation, between init() and end(); 

public: 

    void init(); 
    void end(); 
}; 

void TimerHao::init() 
{ 
    if(flag!=0) { throw runtime_error("ERROR!!! Cannot initial the timer before it is ended!"); } 
    ... 
    flag=1; 
} 

void TimerHao::end() 
{ 
    if(flag!=1) { throw runtime_error("ERROR!!! Cannot end the timer before it is initialized!");} 
    ... 
    flag=0; 
} 

我可以通過使用代碼:

TimerHao timerhao; 
timerhao.init(); 
... 
timerhao.end(); 
... 
timerhao.init(); 
... 
timerhao.end(); 
... 

我不喜歡標誌設置爲一個整數,我需要閱讀的註釋,以瞭解其含義。實際上,我在我的代碼中使用了這種標誌,例如標誌可以是0,1,2,3,5,每個數字意味着不同的事物。有時候,我對自己的代碼感到困惑,我必須仔細閱讀註釋以瞭解我在做什麼。有沒有一種明確的方法來處理這個標誌?謝謝。

+0

如何使用'enum'來代替? –

+0

你想要的是一個枚舉 – UKMonkey

+0

爲它添加一個'enum'。 –

回答

4

您可以添加一個枚舉,並在代碼中使用該值,使代碼是不言自明:

class TimerHao 
{ 
private: 

    enum flag_states 
    { 
     FLAG_STATE_NOT_STARTED = 0, 
     FLAG_STATE_IN_ACCUMULATION, 
     // etc 
    }; 

    double seconds; 
    flag_states flag = FLAG_STATE_NOT_STARTED; //0: Have not start accumulation. 1: In accumulation, between init() and end(); 

public: 

    void init(); 
    void end(); 
}; 

void TimerHao::init() 
{ 
    if(flag != FLAG_STATE_NOT_STARTED) { throw runtime_error("ERROR!!! Cannot initial the timer before it is ended!"); } 

    flag = FLAG_STATE_IN_ACCUMULATION; 
} 

void TimerHao::end() 
{ 
    if(flag != FLAG_STATE_IN_ACCUMULATION) { throw runtime_error("ERROR!!! Cannot end the timer before it is initialized!");} 

    flag= FLAG_STATE_NOT_STARTED; 
} 

如果你有機會獲得C++ 11,你甚至可以使一個範圍的列舉和禁止鑄造:

class TimerHao 
{ 
private: 

    enum class flag_states 
    { 
     FLAG_STATE_NOT_STARTED = 0, 
     FLAG_STATE_IN_ACCUMULATION, 
     // etc 
    }; 

    double seconds; 
    flag_states flag = flag_states::FLAG_STATE_NOT_STARTED; //0: Have not start accumulation. 1: In accumulation, between init() and end(); 

public: 

    void init(); 
    void end(); 
}; 

void TimerHao::init() 
{ 
    if(flag != flag_states::FLAG_STATE_NOT_STARTED) { throw runtime_error("ERROR!!! Cannot initial the timer before it is ended!"); } 

    flag = flag_states::FLAG_STATE_IN_ACCUMULATION; 
} 

void TimerHao::end() 
{ 
    if(flag != flag_states::FLAG_STATE_IN_ACCUMULATION) { throw runtime_error("ERROR!!! Cannot end the timer before it is initialized!");} 

    flag= flag_states::FLAG_STATE_NOT_STARTED; 
} 
+0

爲什麼不把'flag'存儲爲'flag_states'而不是'int'? – wasthishelpful

+0

@wasthishelpful mhm,編輯。 –

+0

謝謝@Gill Bates,這真的很棒。 –