Chinaunix首页 | 论坛 | 博客
  • 博客访问: 50524
  • 博文数量: 15
  • 博客积分: 265
  • 博客等级: 二等列兵
  • 技术积分: 130
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-23 17:05
文章分类

全部博文(15)

文章存档

2014年(1)

2013年(3)

2012年(11)

我的朋友

分类: C/C++

2012-12-04 15:03:08

小括号重载operator。

点击(此处)折叠或打开

  1. #include <iostream>
  2. using namespace std;

  3. class Time
  4. {
  5. public:
  6.     int h;
  7.     int m;
  8.     int s;

  9.     Time( int h = 0, int m = 0, int s = 0 )
  10.     {
  11.         operator()(h,m,s);
  12.     }

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

  18.     //用户自定义转换
  19.     operator int()
  20.     {
  21.         return h*3600 + m*60 + s;
  22.     }

  23.     //小括号重载 版本1
  24.     void operator()(int h)
  25.     {
  26.         operator()(h,0,0);
  27.     }

  28.     //小括号重载 版本2
  29.     void operator()(int h, int m)
  30.     {
  31.         operator()(h,m,0);
  32.     }

  33.     //小括号重载 版本3
  34.     void operator()(int h, int m, int s)
  35.     {
  36.         this->h = h;
  37.         this->m = m;
  38.         this->s = s;
  39.     }

  40.     friend ostream & operator << ( ostream & os, const Time & t )
  41.     {
  42.         os << t.h << "::";
  43.         if ( t.m < 10 )
  44.         {
  45.             os << '0';
  46.         }
  47.         os << t.m << "::";
  48.         if ( t.s < 10 )
  49.         {
  50.             os << '0';
  51.         }
  52.         os << t.s;
  53.         return os;
  54.     }
  55. };

  56. int main()
  57. {
  58.     /*
  59.     ** 注意:t(1),t(1,1),t(1,1,1)的用法
  60.     ** 像不像“函数调用”
  61.     ** 这样的用法称之为仿函数
  62.     ** 仿函数在STL里用得特别多
  63.     */
  64.     Time t;
  65.     cout << t << endl;
  66.     t(1); //小括号重载 版本1
  67.     cout << t << endl;
  68.     t(1,1); //小括号重载 版本2
  69.     cout << t << endl;
  70.     t(1,1,1); //小括号重载 版本3
  71.     cout << t << endl;
  72.     cout << t() << endl; //小括号重载 版本0
  73.     cout << int(t) << endl; //用户自定义转换
  74.     return 0;
  75. }

阅读(967) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~