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!"<<endl;
}
//显示时间函数实现
void Clock::ShowTime()
{
cout<<Hour<<":"<<Minute<<":"<<Second<<endl;
}
//前置单目运算符重载实现
Clock& Clock::operator ++()//前置单目运算符重载函数
{
Second++;
if(Second>=60)
{
Second = Second-60;
Minute++;
if(Minute>=60)
{
Minute = Minute - 60;
Hour++;
Hour=Hour%24;
}
}
return *this;
}
//后置单目运算符重载实现
Clock Clock::operator ++(int)//后置单目运算符重载
{
Clock old = *this;
++(*this);
return old;
}
void main()
{
Clock myClock(23,59,59);
cout<<"First time output:";
myClock.ShowTime();
cout<<"Show myClock++:";
(myClock++).ShowTime();
cout<<"Show ++myClock:";
(++myClock).ShowTime();
}
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!"<<endl;
}
//显示时间函数实现
void Clock::ShowTime()
{
cout<<Hour<<":"<<Minute<<":"<<Second<<endl;
}
//前置单目运算符重载实现
Clock& Clock::operator ++()//前置单目运算符重载函数
{
Second++;
if(Second>=60)
{
Second = Second-60;
Minute++;
if(Minute>=60)
{
Minute = Minute - 60;
Hour++;
Hour=Hour%24;
}
}
return *this;
}
//后置单目运算符重载实现
Clock Clock::operator ++(int)//后置单目运算符重载
{
Clock old = *this;
++(*this);
return old;
}
void main()
{
Clock myClock(23,59,59);
cout<<"First time output:";
myClock.ShowTime();
cout<<"Show myClock++:";
(myClock++).ShowTime();
cout<<"Show ++myClock:";
(++myClock).ShowTime();
}
------------------
------------------