Automatic conversion from double/int/string to bool in C++

后端 未结 2 1563
终归单人心
终归单人心 2020-12-11 09:49

I\'m a Java programmer who has been trying to learn a bit of C++ on the side to expand on my knowledge. Here is a small code snippet which I think works due to impl

2条回答
  •  旧时难觅i
    2020-12-11 10:30

    All base types can be converted to bool implicitly. Anything that is not 0 is TRUE, and 0 is FALSE.

    For user defined types, if you use pointers, anything that is not NULL is evaluates to TRUE, otherwise FALSE.

    If you use object instances and not pointers, you need to declare operator bool():

    class A
    {
    public:
       operator bool() {return false;};
    };
    
    //....
    
    A a;
    if ( a ) //compiles because of the operator
       //...;
    

提交回复
热议问题