如何正确设置标记

时间:2016-10-04 11:53:19

标签: c++ c++11

我有一个计时器类,在类里面有一个标志。当我们没有调用init()时,flag为0.在我们调用init()之后,它将被设置为1.在调用end()之后,它将被设置回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();
 ...

我不喜欢将标志设置为整数,我需要阅读注释以了解其含义。实际上,我在代码中经常使用这种类型的标志,例如flag可以是0,1,2,3,5,每个数字意味着不同的东西。有时,我对自己的代码感到困惑,我必须仔细阅读评论,以了解我在做什么。有没有一个明确的方法来处理这个标志?谢谢。

1 个答案:

答案 0 :(得分: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;
}