日期:2014-05-16 浏览次数:20796 次
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication14 { class Program { public static void Main(string[] args) { Vector vect1, vect2, vect3; vect1 = new Vector(3.0, 3.0, 1.0); //调用运算符函数 vect2 = new Vector(2.0, -4.0, -4.0); vect3 = vect1 + vect2; //实现运算符重载 Console.WriteLine(vect1.ToString()); Console.WriteLine(vect2.ToString()); Console.WriteLine( vect3.ToString()); } class Vector { private double x, y, z; public double X { get { return x; } set { y = value; } } public double Y { get { return y; } set { y = value; } } public double Z { get { return z; } set { z = value; } } public Vector() { x = 0; y = 0; z = 0; } public Vector(Vector rhs) { x = rhs.x; y = rhs.y; z = rhs.z; } public Vector(double x, double y, double z) { this .x=x ; this .y=y; this.z=z; } public override string ToString() { return "X的坐标是:"+x+"Y的坐标是:"+y+"Y的坐标是:"+z ; } public static Vector operator +(Vector lhs, Vector rhs) //声明运算符重载 { Vector result = new Vector(lhs); result.x += rhs.x; result.y += rhs.y; result.z += rhs.z; return result; } } } }不同的运算符中重载时有不同的要求