Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 是否有一个“问题”;“正常”;C+中的一元逻辑运算符+;_C++_Operators_Logical Operators_Unary Operator - Fatal编程技术网

C++ 是否有一个“问题”;“正常”;C+中的一元逻辑运算符+;

C++ 是否有一个“问题”;“正常”;C+中的一元逻辑运算符+;,c++,operators,logical-operators,unary-operator,C++,Operators,Logical Operators,Unary Operator,我的意思是,我们都知道有否定逻辑运算符,可以这样使用: class Foo { public: bool operator!() { /* implementation */ } }; int main() { Foo f; if (!f) // Do Something } 是否有操作员允许此操作: if (f) // Do Something 我知道这可能不重要,但只是想知道 您可以声明和定义运算符bool(),以便隐式转换为bool,如

我的意思是,我们都知道有否定逻辑运算符
,可以这样使用:

class Foo
{
public:
    bool operator!() { /* implementation */ }
};

int main()
{
    Foo f;
    if (!f)
        // Do Something
}
是否有操作员允许此操作:

if (f)
    // Do Something

我知道这可能不重要,但只是想知道

您可以声明和定义
运算符bool()
,以便隐式转换为
bool
,如果您需要的话

或者写:

if (!!f)
   // Do something
由于
操作符bool()
本身非常危险,我们通常使用以下方法:

在C++11中,我们得到了显式的转换运算符;因此:


我知道我可以这样做,但是没有直接运算符吗?@Mr.TAMER:
operator bool()
不是直接运算符吗?@Mr.TAMER:
如果
要求其条件表达式为
bool
类型,那么您给出的任何内容都将在可能的情况下转换为
bool
。如果(1)
明白了,谢谢:),同样的故事,但是你说的小心是什么意思?我应该更关心什么?@Mr.TAMER:Google for。通过定义运算符bool(),您可以得到您想要的。@maress:是的,我们已经讨论过了。可能重复
operator bool() { //implementation };
class X{
  typedef void (X::*safe_bool)() const;
  void safe_bool_true() const{}
  bool internal_test() const;
public:
  operator safe_bool() const{
    if(internal_test())
      return &X::safe_bool_true;
    return 0;
  }
};
class X{
  bool internal_test() const;
public:
  explicit operator bool() const{
    return internal_test();
  }
};