天天看点

重载运算符++的应用(时间类)

#include

using namespace std;

class Time

{

private:

int hour;

int minute;

int second;

public:

Time(int a=0,int b=0,int c=0)

{

this->hour=a;

this->minute=b;

this->second=c;

}

void Show()

{

cout<<hour<<":"<<minute<<":"<<second<<endl;

}

Time operator ++();//这里定义了这个是Time类的所以在后面再出现的时候也要声明它的类型

Time operator ++(int);//这里的int 是因为++就是x=x+1的意思所以要int是给1的

} ;

Time Time::operator ++()//记住他是time类的并且是Time类中的函数 所以要Time Time ::

{

Time x;

second++;

x.second=second;

x.hour=hour;

x.minute=minute;

return x;//这里不要忘了返回值 否则就白运算了

}

Time Time::operator ++(int)//同上

{

Time x;

x.second=second;

x.hour=hour;

x.minute=minute;

second++;

return x;//这里不要忘了返回值 否则就白运算了

}

int main()

{

Time t1(10,25,52),t2,t3;//定义一个时间对象t1,带参数,t2、t3对象不带参数

t1.Show();

t2=++t1;//使用重载运算符++完成前置++

t1.Show();

t2.Show();

t3=t1++;//使用重载运算符++完成后置++

t3.Show();

t1.Show();

return 0;

}

继续阅读