Lazy, overloaded C++ && operator?

后端 未结 4 588
情歌与酒
情歌与酒 2021-01-18 01:07

I\'m trying to implement my own boolean class, but cannot replicate native semantics for &&. The following contrived code demonstrates the issue:



          


        
4条回答
  •  有刺的猬
    2021-01-18 01:56

    You should not overload bool operator&&, since you lose short circuit evaluation, as you have discovered.

    The correct approach would be to give your class a bool conversion operator

    class MyBool {
     public:
      bool theValue;
      MyBool() {}
      MyBool(bool aBool) : theValue(aBool) {}
      explicit operator bool() { return theValue; }
    };
    

    Note that explicit conversion operators require C++11 compliance. If you do not have this, have a look at the safe bool idiom.

提交回复
热议问题