c++运算符重载

重载为类的成员函数:

返回类型 类名::operator 运算符(形参表)
{
    函数体
}

重载为类的非成员函数:

返回类型 operator 运算符(形参表)
{
    函数体
}

示例:

#include<iostream>
using namespace std;
class Clock //时钟类定义
{
public:
    Clock();
    Clock(int hour,int minute,int second);
    Clock &operator++(); //前置单目运算符重载
    Clock operator++(int);//后置单目运算符重载
    Clock &operator=(const Clock &c);//=运算符重载
    friend ostream &operator<<(ostream &out,const Clock &c);//重载为非成员函数
private:
    int hour,minute,second;
};
Clock::Clock(int hour,int minute,int second)
{
    if(0<hour&&hour<24&&0<minute&&minute<60&&0<=second&&second<60)
    {
        this->hour=hour;
        this->minute=minute;
        this->second=second;
    }
    else
        cout<<"Time error!"<<endl;

}
ostream &operator<<(ostream &out,const Clock &c)
{
    out<<c.hour<<":"<<c.minute<<":"<<c.second;
    return out;
}

Clock &Clock::operator++()
{
    second++;
    if(second>=60)
    {
        second-=60;
        minute++;
        if(minute>=60)
        {
            minute-=60;
            hour=(hour+1)%24;
        }
    }
    return *this;

}
Clock Clock::operator++(int)
{
    Clock old=*this;
    ++(*this);
    return old;
}
Clock &Clock::operator=(const Clock &c2)
{
    this->second=c2.second;
    this->minute=c2.minute;
    this->hour=c2.hour;
    return *this;
}
Clock::Clock():hour(0),minute(0),second(0) {}
int main()
{
    Clock myClock(23,59,59);
    cout<<"First time output:";
    cout<<myClock<<endl;
    cout<<"show myClock++: ";
    cout<<(myClock++)<<endl;
    cout<<"show  ++ myClock:";
    cout<<++myClock<<endl;
    Clock newClock;
    newClock=myClock;
    cout<<"show newClock=myClock:";
    cout<<newClock<<endl;
    return 0;

}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值