C# 運算子過載

iamzxf發表於2015-04-22

    使用者自定義了類以後,如果想在例項化的物件上進行某些運算,有時需要借用現有的運算子,這時需要對相關的運算子在使用者定義的類中進行重定義,稱為運算子的過載。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace chongzai
{
    class Point
    {
        public int x, y;
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        public static Point operator +(Point pt1, Point pt2)
        {
            return new Point(pt1.x + pt2.x, pt1.y + pt2.y);
        }

        public static Point operator -(Point pt1, Point pt2)
        {
            return new Point(pt1.x - pt2.x, pt1.y - pt2.y);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            Point pt1 = new Point(10, 20);
            Point pt2 = new Point(20, 30);
            Point pt3 = pt1 + pt2, pt4 = pt1 - pt2;

            Console.WriteLine("{0},{1}", pt3.x, pt3.y);
            Console.WriteLine("{0},{1}", pt4.x, pt4.y);

            Console.ReadLine();
        }
    }
}


相關文章