C++ operator bool

雕虫小技:

#include <iostream>

struct A{
    operator bool(){
        return false;
    }
};

int main()
{
    A a{};
    if(!a){
        std::cout<<"1";
    }
}

还记得当年大明河畔的夏老板吗?

ifstream in(..);
if(!in){
..
}

 

另外还可以这样写:

 

#include <iostream>

using namespace std;

struct A{
        operator bool(){
                cout<<"operator bool\n";
                return false;
        }
};
struct B{
        operator !(){
                cout<<"operator !\n";
                return true;
        }
};

int main()
{
        A a{};
        if(!a){
                cout<<"a\n";
        }
        B b;
        if(!b){
                cout<<"b\n";
        }
}

  他们的区别很明显,调用时,operator bool 可以if(a)或if(!a),而operator !只能用if(!a)。

  如果一个类同时实现了这俩,调用时用if(!a),则会优先调用operator!。

posted @ 2017-03-24 17:59  开学五年级了  阅读(523)  评论(0编辑  收藏  举报