【问题标题】:How to set the boolean value for a c++ class?如何为 C++ 类设置布尔值?
【发布时间】:2020-10-13 13:29:44
【问题描述】:

我想知道如何设置类的布尔值。我在其他人的代码中看到过这个,但我自己不知道怎么做。格式是这样的:

class myClass{
   //...
};
myClass getClass(){
  myClass myclass;
  //...
  return myclass;
}

int main(int argc, char **argv){
  myClass myclass;
  myclass = getClass();
  if(myclass){
    //do stuff
  }
  //...
  if(!myclass){
    //do other stuff
  }
  return 0;
}

【问题讨论】:

  • 你可以在你的类中定义explicit operator bool() const。请参阅stackoverflow.com/a/4600316/1718575,其中有一些关于隐式转换的警告。
  • 谢谢。这正是我所需要的。

标签: c++ class


【解决方案1】:

您需要为您的班级提供到bool 的转换函数,如下所示:

class myClass{
   public:
   explicit operator bool() const { /* ... */ }
};

最好进行转换explicit,避免意外转换。在if 语句中使用它很好,因为这被认为是显式上下文。

【讨论】:

    【解决方案2】:

    我看到你的课程设计可以改进。 您可以只创建对象的pointer 而不是创建本地对象,这会隐式处理并且您不会陷入隐式转换的混乱。

    对于boolean 值[如果您真的需要它],您可以直接将bool 作为任何附加逻辑的类成员。这直接在代码中表达了意图。

    class myClass{
     ...
     bool isOn;
    
    public:
     bool getIsOn(){
         return isOn;
     }
    };
    

    司机:

    int main(int argc, char **argv){
      std::unique_ptr<myClass> obj =  std::make_unique<myClass>();
      if(obj){
        //do stuff
      }
      //...
      if(!obj){
        //do other stuff
      }
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-24
      • 2013-02-08
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多