I'm planning to have two bool class members (m_alive #define object2.m_death= !object2.m_alive;// ...
So here you have the main 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 of how-to keep'em updated is welcome, as well as any other ways of implementing my idea. Thanks in advance!
欢迎任何关于如何保持更新的建议,以及实现我的想法的任何其他方式。提前致谢!
Eduardo
PD: While re-reading my question, enumerated types have just came to my mind.
PD:在重新阅读我的问题时,我想到了枚举类型。
It would emply checking myobject.m_status==dead or myobject.m_status==alive, being dead and alive possible values of dead_or_alive enum-type class member dead_or_alive m_status.
它将主要检查myobject.m_status == dead或myobject.m_status == alive,dead_or_alive枚举类成员dead_or_alive m_status的死和活值。
Could this be a nicer approach to what I'm seeking, despite being a bit longer syntax?
尽管语法有点长,但这对我正在寻求的方法是否更好?
Final edit:
Thanks to all who commented and answered. Here's the solution I've finally adopted:
感谢所有评论和回答的人。这是我最终采用的解决方案:
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};3 个解决方案
#1
10
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()) // ...}#2
6
You're trying to violate the "Single Source of Truth" best practice, by keeping 2 copies of the same information.
您试图通过保留2份相同信息来违反“单一真理来源”最佳做法。
If you're looking for clarity (and you don't find if(m_alive) and if(!m_alive) clear enough) then add custom getters to myclass:
如果你正在寻找清晰度(并且你没有找到if(m_alive)和if(!m_alive)是否足够清楚)那么将自定义getter添加到myclass:
bool isAlive() const { return m_alive; }bool isDead() const { return !m_alive; }#3
1
You can implement this by using a setter for changing the variables:
您可以使用setter更改变量来实现此目的:
// optional settersvoid setDead() { setDead(true); }void setAlive() { setDead(false); }// main settervoid setDead(bool isDead) { m_alive = !(m_dead = isDead);}