C# Vector定义、operator 使用c#操作符重载

/// <summary>
    /// 向量类
    /// </summary>
    public class Vector
    {
        public double x, y, z;


        public Vector()
        {

        }


        public Vector(double _x, double _y, double _z)
        {
            x = _x;
            y = _y;
            z = _z;
        }


        /// <summary>
        /// 求向量长度
        /// </summary>
        /// <returns></returns>
        public double magnitude()
        {
            return Math.Sqrt(x * x+ y * y+z * z);
        }


        /// <summary>
        /// 求单位向量
        /// </summary>
        /// <returns></returns>
        public Vector normal()
        {
            double k = 1 / magnitude();
            Vector d = new Vector(k * x, k * y, k * z);
            return d;         
        }
        
        /// <summary>
        /// 向量和
        /// </summary>
        /// <param name="v1">向量1</param>
        /// <param name="v2">向量2</param>
        /// <returns>新向量</returns>
        public static Vector operator +(Vector v1, Vector v2)
        {
            Vector d = new Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
            return d;
           
        }
        /// <summary>
        /// 求反向量
        /// </summary>
        /// <param name="v">向量</param>
        /// <returns>新向量</returns>
        public static Vector operator -(Vector v)
        {
            Vector d = new Vector(-v.x, -v.y, -v.z);
            return d;
           
        }
        /// <summary>
        /// 求向量
        /// </summary>
        /// <param name="v1"></param>
        /// <param name="v2"></param>
        /// <returns></returns>
        public static Vector operator -(Vector v1, Vector v2)
        {
            Vector d = new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
            return d;            
        }


        public static Vector operator *(Vector v, double k)
        {
            Vector d = new Vector(k * v.x, k * v.y, k * v.z);
            return d;
            
        }
        public static Vector operator *(double k, Vector v)
        {
            Vector d = new Vector(k * v.x, k * v.y, k * v.z);
            return d;
            
        }
        public static Vector operator /(Vector v, double k)
        {
            Vector d=new Vector(v.x / k, v.y / k, v.z / k) ;
            d.x =v.x / k;
            d.y =v.y / k;
            d.z =v.z / k;
            return d;          
        }


        public static double operator ^(Vector v1, Vector v2)
        {
            return v2.x + v2.x + v1.y + v2.y + v1.z + v2.z;
        }
        public static Vector operator *(Vector v1, Vector v2)
        {
            Vector d = new Vector(v1.y * v2.z - v2.z * v2.y,
                v1.z * v2.x - v1.x * v2.z,
                v1.x * v2.y - v1.y * v2.x);
            return d;           
        }              
    }


在C#里可以使用LIST替代C++的Vector.

http://www.cnblogs.com/xugang2008/archive/2010/03/03/1677051.html


 细心的朋友可能发现,C#虽然可以重载操作符,但和C++比较起来,却有很大的不同。定义的时候重载操作符方法必须是static,而且至少有一个参数(一目和二目分别是一个和两个),C#C++比起来,最重要的特征是:<>==!=truefalse必须成对出现,即重载了“<”就必须重载“>”,重载了“==”就必须重载“!=”,重载了“true”就必须重载“false”;另外,还必须实现基类object的两个虚方法:GetHashCode()和Equals(object obj)。

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");
    }
  }
}

C#操作符重载是什么?

是指允许用户使用用户定义的类型编写表达式的能力。

例如,通常需要编写类似于以下内容的代码,以将两个数字相加。很明显,sum 是两个数字之和。

int i = 5; 
int sum = i + j;

如果可以使用代表复数的用户定义的类型来编写相同类型的表达式,那当然是最好不过了:

Complex i = 5;
Complex sum = i + j;

运算符重载允许为用户定义的类型重载(即指定明确的含义)诸如“+”这样的运算符。如果不进行重载,则用户需要编写以下代码:

Complex i = new Complex(5);
Complex sum = Complex.Add(i, j);

此代码可以很好地运行,但 Complex 类型并不能象语言中的预定义类型那样发挥作用。

在我看来是操作符重载是让struct、class、Interface等能够进行运算。

如时实现C#操作符重载。

先写关键词public和static,后跟返回类型,后跟operator关键词,后跟要声明的操作符符号,最后在对一对圆括号中添加恰当的参数。

如下例中的struct Hour中的public static Hour operator+ (Hour lhs,Hour rhs){...}

C#操作符重载方法:

1、编写操作符重载方法。

2、实例化后,进行操作符运算

下边用C#操作符重载代码进行说明:

 
 
  1. class Program  
  2. {  
  3. static void Main(string[] args)  
  4. {  
  5. Hour hrValue1 = new Hour(10);  
  6. Hour hrValue2 = new Hour(20);  
  7.  
  8. //2、得到两个Hour相加结果  
  9. Hour hrSum = hrValue1 + hrValue2;  
  10.  
  11. //得到Hour+Int的结果  
  12. Hour hrSumInt = hrValue1 + 10;  
  13.  
  14. //得到Int+Hour的结果  
  15. Hour hrIntSum = 11 + hrValue2;  
  16. Console.WriteLine("hrValue1 +  hrValue2 = {0}", hrSum.iValue);  
  17. Console.WriteLine("hrValue1 +  10  = {0}", hrSumInt.iValue);  
  18. Console.WriteLine("11 +  hrValue2  = {0}", hrIntSum.iValue);  
  19. Console.ReadKey();  
  20. }  
  21. struct Hour  
  22. {  
  23. private int value;  
  24. //此构造函数根据int值创建Hour类 ,C#操作符重载 
  25. public Hour(int iValue)  
  26. {  
  27. this.value = iValue;  
  28. }  
  29. //定义一个属性,便于取用value值  
  30. public int iValue  
  31. {  
  32. get 
  33. {  
  34. return value;  
  35. }  
  36. } //C#操作符重载
  37. //1、声明一个二元操作符,将两个Hour类加到一起   
  38. public static Hour operator+ (Hour lhs,Hour rhs)  
  39. {  
  40. return new Hour(lhs.value + rhs.value);  
  41. }  
  42.  
  43. /*  
  44. 操作符是public的。所有操作符都必须是public的  
  45.  
  46. 操作符是static的。所有操作符都必须是static的,操作永远不具有多态性,  
  47.  
  48. 面且不能使用virtual、abstract、override或者sealed修饰符。  
  49.  
  50. 二元操作符(比如+)有两个显式参数;一元操作符有一个显式的参数  
  51.  
  52. 我们有了public Hour(int iValue)构造函数,就可以将一个int与Hour相加,只是首先要将int转换成为Hour  
  53.  
  54. hour a= ;  
  55.  
  56. int b= ;  
  57.  
  58. Hour sum=a+new Hour(b);  
  59.  
  60. 虽然上述代码完全有效,但相较于让一个Hour和一个int直接相加它即不清晰也不准确。  
  61.  
  62. 为了使Hour可以+ int,必须声明一个二元操作符+,它的第一个参数是Hour,第二个参数是一个int。  
  63.  C#操作符重载
  64.  */ 
  65. public static Hour operator+ (Hour lhs,int rhs)  
  66. {  
  67. return lhs + new Hour(rhs);  
  68. }  
  69. //使一个int 可以+hour。  
  70. public static Hour operator +(int lhs, Hour rhs)  
  71. {  
  72. return new Hour(lhs)+rhs;  
  73. }  
  74. }  

C#操作符重载示例2:

 
 
  1. struct Hour  
  2. {  
  3. public int iValue;  
  4. //构造函数  
  5. public Hour(int initialValue)  
  6. {  
  7. this.iValue = initialValue;  
  8. }  
  9. //1、定义操作符重载(一元操作符)  
  10. public static Hour operator ++ (Hour huValue)  
  11. {  
  12. huValue.iValue++;  
  13. return huValue;  
  14. }  //C#操作符重载
  15.  
  16. //==操作符是二元操作符,必须带有两个参数  
  17. public static bool operator==(Hour lhs,Hour rhs)  
  18. {  
  19. return lhs.iValue == rhs.iValue;  
  20. }  
  21. public static bool operator!=(Hour lhs,Hour rhs)  
  22. {  
  23. return lhs.iValue != rhs.iValue;  
  24. }  
  25. }  
  26.  
  27. //++操作符有前缀和后缀的形式,C#能智能地为前缀后后缀使用同一个操作符。  
  28.  
  29. static void Main(string[] args)  
  30. {  
  31. //2、实例化类  ,C#操作符重载
  32.  
  33. Hour hu = new Hour(10);  
  34. //3、  
  35. //操作符重载  
  36.  
  37. hu++;  
  38. //输出重载后的结果  
  39.  
  40. Console.WriteLine("Hu++ = {0}", hu.iValue);  
  41. //C#操作符重载  
  42.  
  43. ++hu;  
  44. //输出重载后的结果  
  45.  
  46. Console.WriteLine("Hu++ = {0}", hu.iValue);  
  47.  
  48. Console.ReadKey();  
  49. }  

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值