Saving two bool class elements with opposite values

I plan to have two classes of members of bool ( m_aliveand m_dead) that their values have always been opposed. This may seem like something stupid (actually it can just be stupid), but as you can see in the code below, but I'm really looking to have a clearer way to check the status of the object depending on the circumstances, and that was it would be helpful not to print !m_aliveor !m_dead. So yes, I really don't need both members, but I can't think of an easier way to do this.

The first thought that came to my mind is to create a function that changes the state of one of them, if the other also changes, but I'm sure there should be a simpler, simpler and faster way to save each of them has the correct meaning.

AFAIK, this is impossible to do with help define, since there would be as many of them as different objects that I plan to create and do not seem practical.

#define object1.m_death= !object1.m_alive;
#define object2.m_death= !object2.m_alive;
// ...

So here you have the basic idea of ​​having both members:

class myclass
{
    public:
    // (...)
    private:
        bool m_alive;
        bool m_death;   // Always !m_alive
};

int main()
{
    myclass myobject;
    // (...)
    if (myobject.m_dead)
    //...
    if (myobject.m_alive)   // clearer than !myobject.m_dead()
    // ...
}

Any suggestions for updating How 'to Keep'em are welcome, as well as any other ways to implement my idea. Thanks in advance!

Eduardo

PD: re-reading my question, the listed types just came to my mind.

myobject.m_status==dead myobject.m_status==alive, dead alive dead_or_alive enum-type dead_or_alive m_status.

, , , ?


:

, . , , , :

enum Piece_status:bool{     dead= false,    alive= true};

class Piece
{
    public:
        bool isAlive() const    {return  m_status;}
        bool isDead()  const    {return !m_status;}
    protected:      
        Piece_status        m_status;   // dead=false, alive=true
};
+4
3
class myclass
{
    public:
        bool isAlive() const { return m_alive; }
        bool isDead() const { return !m_alive; }
    private:
        bool m_alive;
};

int main()
{
    myclass myobject;
    // (...)
    if (myobject.isDead())
    //...
    if (myobject.isAlive())
    // ...
}
+10

" " , 2 .

( if(m_alive) if(!m_alive)), myclass:

bool isAlive() const { return m_alive; }
bool isDead() const { return !m_alive; }
+6

This can be implemented using the installer to change variables:

// optional setters
void setDead() { setDead(true); }
void setAlive() { setDead(false); }

// main setter
void setDead(bool isDead) {
    m_alive = !(m_dead = isDead);
}
+1
source

Source: https://habr.com/ru/post/1665615/


All Articles