C - Operator overload

Through operator overloading, we can use standard operators for our designed classes, such as +, - and so on. This is called overloading, because when using specific parameter types, we provide our own implementation code for these operators in the same way as overloading methods, and also provide different parameters for methods with the same name. The operation overload character definition > also needs to define <; the operator = =,! = also needs to be defined. At the same time, it is better to override the GetHashCode() method and the Equals(Object o) method.

class Time
    {
        private int hour;
        private int min;

        public Time(int hour, int min)
        {
            this.hour = hour;
            this.min = min;
        }
        public void Add(Time t)
        {
            this.hour = this.hour + t.hour + (t.min + this.min) / 60;
            this.min = (this.min + min) % 60;
        }
        public override string ToString()
        {
            return string.Format("{0,2}:{1,2}", hour, min);
        }
        public override bool Equals(object obj)
        {
            return this == (Time)obj;
        }
        public override int GetHashCode()
        {
            return this.GetTotalMins();
            //return 1;
        }
        public int GetTotalMins()
        {
            return hour * 60 + min;
        }
        public static Time operator +(Time t1, Time t2)
        {
            Time result = new Time(0, 0);
            result.hour = t1.hour + t2.hour + (t1.min + t2.min) / 60;
            result.min = (t1.min + t2.min) % 60;
            return result;
        }
        public static bool operator >(Time t1, Time t2)
        {
            if (t1.GetTotalMins() > t2.GetTotalMins())
                return true;
            return false;
        }
        public static bool operator <(Time t1, Time t2)
        {
            if (t1.GetTotalMins() < t2.GetTotalMins())
                return true;
            return false;
        }
        public static bool operator >=(Time t1, Time t2)
        {
            return !(t1 < t2);
        }
        public static bool operator <=(Time t1, Time t2)
        {
            return !(t1 > t2);
        }
        public static bool operator ==(Time t1, Time t2)
        {
            return t1.GetTotalMins() == t2.GetTotalMins();
        }
        public static bool operator !=(Time t1, Time t2)
        {
            return !(t1==t2);
        }      
    }

Keywords: Programming

Added by Wien on Tue, 07 Jan 2020 16:49:11 +0200