小括号重载

#include <iostream>
using namespace std;

class Time
{
public:
    int h;
    int m;
    int s;

    Time( int h = 0, int m = 0, int s = 0 )
    {
        operator()(h,m,s);
    }

    //小括号重载 版本0 注意和下面用户自定义转换区别
    int operator()()
    {
        return h*3600 + m*60 + s;
    }

    //用户自定义转换
    operator int()
    {
        return h*3600 + m*60 + s;
    }

    //小括号重载 版本1
    void operator()(int h)
    {
        operator()(h,0,0);
    }

    //小括号重载 版本2
    void operator()(int h, int m)
    {
        operator()(h,m,0);
    }

    //小括号重载 版本3
    void operator()(int h, int m, int s)
    {
        this->h = h;
        this->m = m;
        this->s = s;
    }

    friend ostream & operator << ( ostream & os, const Time & t )
    {
        os << t.h << "::";
        if ( t.m < 10 )
        {
            os << '0';
        }
        os << t.m << "::";
        if ( t.s < 10 )
        {
            os << '0';
        }
        os << t.s;
        return os;
    }
};

int main()
{
    /*
    ** 注意:t(1),t(1,1),t(1,1,1)的用法
    ** 像不像“函数调用”
    ** 这样的用法称之为仿函数
    ** 仿函数在STL里用得特别多
    */
    Time t;
    cout << t << endl;
    t(1);                    //小括号重载 版本1
    cout << t << endl;
    t(1,1);                  //小括号重载 版本2
    cout << t << endl;
    t(1,1,1);                //小括号重载 版本3
    cout << t << endl;
    cout << t() << endl;     //小括号重载 版本0
    cout << int(t) << endl;  //用户自定义转换
    return 0;
}

1.小括号重载用得最多的地方,自然还是“仿函数”,这个有空可以专门写一章

2.在使用用户自定义转换,可以想一下:将double型转换为int型的过程。

 

参考资料:

    1.http://blog.sina.com.cn/s/blog_5d2a81780100r9q0.html

转载于:https://www.cnblogs.com/c007136/archive/2012/05/22/2513790.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值