C++ 单目运算符 ++ 重载多态问题

来源:百度知道 编辑:UC知道 时间:2024/05/14 01:45:23
程序摘自C++语言程序设计(第三版) 清华大学出版社 (郑莉等编)

//程序开始
#include <iostream>
using namespace std;
class Clock//类声明
{
public:
Clock(int newh=0, int newm=0, int news= 0);
void ShowTime();
Clock& operator ++();
Clock operator ++(int);
private:
int Hour,Minute,Second;
};

Clock::Clock(int newh, int newm, int news)/构造函数
{
if (0<= newh && newh<24 && 0<=newm && newm<60 && 0<=news &&news<60)
{
Hour=newh;
Minute=newm;
Second=news;
}
else
cout<<"Time Error!";
}

void Clock::ShowTime()
{
cout<<Hour<<":"<<Minute<<":"<<Second<<endl;
}

Clock& Clock:: operator ++()//前置单目运算符重载函数
{
Second ++;
if(Second>=60)
{
Second-=60;
Minute ++;
if (Minute>=60)

1:前置即++a,是可以做左值的,因此返回时是*this,比如说++(++a)时如果不是返回的是*this第二次++就不可能应用在a身上。
2:因为如果直接用就不是后置的含义了,后置是先将变量的值做为表达式的值确定下来,再将变量加一,这是原本后置运算含义,如果如同你写的:
Clock Clock:: operator ++(int)
{
++(*this);
return *this;
}
是直接返回增加后的结果,没有对做为表达式的值确定下来!
这样解释不知道你是否明白?