标题:
C++语言简单的运算符重载
[打印本页]
作者:
daming
时间:
2014-12-30 01:59
标题:
C++语言简单的运算符重载
本帖最后由 daming 于 2014-12-30 02:15 编辑
#include<iostream>
using namespace std;
class Clock //时钟类定义
{
public: //外部接口
Clock(int H=0,int M=0,int S=0);
void show_time();
Clock& operator ++(); //前置单目运算符重载
Clock operator ++(int); //后置单目运算符重载
private: //私有数据成员
int Hour,Minute,Second;
};
Clock::Clock(int H,int M,int S) //构造函数
{
if((H >=0&&H <=23)&&(M >=0&&M <=59)&&(S >=0&&S <=59))
{
Hour=H;
Minute=M;
Second=S;
}
else
cout<<"Time error!"<<endl;
}
void Clock::show_time() //显示时间函数
{
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;
}
int main()
{
Clock A(23,59,59);
cout<<"First time output:";
A.show_time();
cout<<"Show A++:";
(A++).show_time();
cout<<"show ++A:";
(++A).show_time();
}
复制代码
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1