77家的会客2010

c#操作符重载!
Weather:十度有风天
using System;

class TimeSpan
{
  private uint totalSeconds;
  private const uint SecondsInHour=3600;
  private const uint SecondsInMinute=60;

  //构造函数
  public TimeSpan()
   {
    totalSeconds=0;
   }

  public TimeSpan(uint initialHours,uint initialMinutes,uint initialSeconds)
   {
    totalSeconds=initialHours*SecondsInHour+initialMinutes*SecondsInMinute+initialSeconds;
   }
  //属性
  public uint Seconds
   {
    get
     {
      return totalSeconds;
     }
    set
     {
      totalSeconds=value;
     }
   }
  //方法
  public void PrintHourMinSec()
   {
    uint hours;
    uint minutes;
    uint seconds;

    hours=totalSeconds/SecondsInHour;
    minutes=(totalSeconds%SecondsInHour)/SecondsInMinute;
    seconds=(totalSeconds%SecondsInHour)%SecondsInMinute;

    Console.WriteLine("{0} Hours {1} Minutes {2} Seconds",hours,minutes,seconds);
   }

  //操作符重载
  public static TimeSpan operator + (TimeSpan timeSpan1,TimeSpan timeSpan2)
   {
    TimeSpan sumTimeSpan=new TimeSpan();
    sumTimeSpan.Seconds=timeSpan1.Seconds+timeSpan2.Seconds;
    return sumTimeSpan;
   }
  public static TimeSpan operator ++ (TimeSpan timeSpan1)
   {
    TimeSpan timeSpanIncremented=new TimeSpan();
    
    timeSpanIncremented.Seconds=timeSpan1.Seconds+1;
    return timeSpanIncremented;
   }
  public static bool operator > (TimeSpan timeSpan1,TimeSpan timeSpan2)
   {
    return (timeSpan1.Seconds>timeSpan2.Seconds);
   }
  public static bool operator < (TimeSpan timeSpan1,TimeSpan timeSpan2)
   {
    return (timeSpan1.Seconds<timeSpan2.Seconds);
   }
  public static bool operator == (TimeSpan timeSpan1,TimeSpan timeSpan2)
   {
    return (timeSpan1.Seconds==timeSpan2.Seconds);
   }
  public static bool operator != (TimeSpan timeSpan1,TimeSpan timeSpan2)
   {
    return (timeSpan1.Seconds!=timeSpan2.Seconds);
   }
}

class TimeSpanTest
{
  public static void Main()
   {
    TimeSpan someTime;
    TimeSpan totalTime=new TimeSpan();
    TimeSpan myTime=new TimeSpan(2,40,45);
    TimeSpan yourTime=new TimeSpan(1,20,30);

    totalTime+=yourTime;
    totalTime+=myTime;

    Console.Write("Your time:     ");
    yourTime.PrintHourMinSec();
    Console.Write("My time:    ");
    myTime.PrintHourMinSec();
    Console.Write("Total race time: ");
    totalTime.PrintHourMinSec();

    if (myTime>yourTime)
        Console.WriteLine("\nI spent more time than you did");
    else
        Console.WriteLine("\nYour spent more time than I did");
    
    myTime++;
    ++myTime;
    Console.Write("\nMy time after two increments: ");
    myTime.PrintHourMinSec();

    someTime=new TimeSpan(1,20,30);
    if (yourTime==someTime)
     {
      Console.WriteLine("\nSpan of someTime is equal to span of yourTime");
     }
    else
     {
      Console.WriteLine("\nSpan of someTime is not equal to span of yourTime");
     }
   }
}
历史上的今天: [2007/03/31]Ghook.dll,svchost.exe病毒解决方法

[c#操作符重载!]的回复

Post a Comment~