隐式转换构造函数、仿函数、转换函数实例

class B {
public:
    //隐式转换
    B(int i)
    {
        cout << i << endl;
        data = i;
    }
    //仿函数
    bool operator() (int i)
    {
        cout << i << endl;
        return i > 0;
    }
    //类型转换函数
    operator string()
    {
        return "class_string";
    }
private:
    int data;
};

int main() {
    B inst = 100;
    bool temp = inst(-100);
    if (temp) {
        cout << "hello operator" << endl;
    }

    string str = inst;
    cout << str << endl;

    getchar();
    return 0;
}

  类型转换函数

  operator 目标类型()

  {

    ...

    return 目标类型的数据;

  }

posted @ 2017-03-13 13:35  略加思索的河马  阅读(299)  评论(0编辑  收藏  举报