关于C++的operator的学习笔记

#include <iostream>
using namespace std;
#include "Time.h"
Time::Time():myHours(12),myMinutes(0),myAMorPM('P'),myMilTime(0){}
Time::Time(unsigned initHours,unsigned initMinutes,unsigned initAMPM)
{
 if(initHours >=1 &&initHours <= 12&&initMinutes >= 0&& initMinutes <= 59&&(initAMPM == 'P'||initAMPM== 'A'))
 {
  myHours = initHours;
  myMinutes = initMinutes;
  myAMorPM = initAMPM;
  myMilTime = initHours * 100 + initMinutes + (initAMPM == 'P'?1200:0);
 }
 else
  cerr<<"****Invalid initial values****\n";
 
}
void Time::display()const
{
 cout<<myHours<<":"<<(myMinutes > 10?"":"0")<<myMinutes<<" "<<myAMorPM<<".M"<<endl;
}
ostream& operator <<(ostream& out,const Time &T)//必须为成员函数,否则调用cout.operator<<(mealTime);函数,这表示operator<<()必须是类ostream的一个成员,而不是Time的一个类
{
 T.display();
 return out;
}
int main()
{
 Time t;
 cout<<t;
 system("pause");
}

posted @ 2012-07-26 12:01  dyhui1992  阅读(149)  评论(0编辑  收藏  举报