C++ 运算符重载

2024-01-09 21:59:56

(Operator) 加分? 减法? []的重载?

#include <iostream>
using namespace std;

class time1
{
    public:
        time1(){shi=0;fen=0;miao=0;}
        time1(int shi, int fen, int miao)
        {
            this->shi = shi;
            this->fen = fen;
            this->miao = miao;
        }
        time1 operator+ (time1 &i)
        {
            time1 ti;
            ti.shi = this->shi+i.shi;
            ti.fen = this->fen+i.fen;
            ti.miao = this->miao+i.miao;
            if(ti.miao >= 60)
            {
                ti.miao=ti.miao-60;
                ti.fen = ti.fen+1;
            }
            return ti;
        }
        time1 operator- (time1 &i)
        {
            time1 tp;
            tp.shi = this->shi-i.shi;
            tp.fen = this->fen-i.fen;
            tp.miao = this->miao-i.miao;
            return tp;
        }
        time1 operator+ (int i)
        {
            time1 tp;
            tp.shi = this->shi;
            tp.fen = this->fen;
            tp.miao = this->miao+i;
            if(tp.miao >= 60)
            {
                tp.miao=tp.miao-60;
                tp.fen = tp.fen+1;
            }
            return  tp;

        }
        int operator[](int i)
        {
            int sex = 0;
            if(i == 0)
            {
            sex = this->miao;
            }
            else if(i == 1)
            {
                sex = this->fen;
            }
            else
            {
                sex = this->shi;
            }
            return sex;
        }



        void show(){cout<<shi<<":"<<fen<<":"<<miao<<endl;}
    private:
        int shi;
        int fen;
        int miao;

};

int main()
{
    time1 t1(1,2,30);
    time1 t2(2,3,40);
    time1 t3;
    time1 t4;                                                            
    t3 = t1 + t2;
    t4 = t2 - t1;
    t3.show();
    t3 = t1 + 10;
    t4.show();
    t3.show();
    int sec = t1[0];
    cout<<"t1[0]="<<sec<<endl;
    sec  = t1[1];
    cout<<"t1[1]="<<sec<<endl;



    return 0;
}

文章来源:https://blog.csdn.net/weixin_64965464/article/details/135415763
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。