操作符重载 (operator)

 

 

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

namespace ConsoleApp
{
    class operatorSample
    {
        //public static void Main()
        //{
        //    //重载操作符test
        //    operatorTest ot = new operatorTest();
        //    ot.Run();
        //    Console.Read();
        //}
    }

    //-----------------------------------------------------------------------------
    //重载操作符
    public class operatorTest
    {
        public void Run()
        {
            Student s1 = new Student(20, "Tom");
            Student s2 = new Student(18, "Jack");
            Student s3 = s1 + s2;

            s3.sayPlus();
            (s1 - s2).sayMinus();
        }
    }

    public class Student
    {
        public Student() { }
        public Student(int age, string name)
        {
            this.name = name;
            this.age = age;

        }
        private string name;
        private int age;

        public void sayPlus()
        {
            System.Console.WriteLine("{0} 年龄之和为:{1}", this.name, this.age);

        }
        public void sayMinus()
        {
            System.Console.WriteLine("{0} 年龄之差为:{1}", this.name, this.age);
        }

        //覆盖“+”操作符
        public static Student operator +(Student s1, Student s2)
        {
            return new Student(s1.age + s2.age, s1.name + " And " + s2.name);
        }
        //覆盖“-”操作符
        public static Student operator -(Student s1, Student s2)
        {
            return new Student(Math.Abs(s1.age - s2.age), s1.name + "And" + s2.name);
        }
    }
}

 

posted @ 2012-11-29 15:17  streetpasser  阅读(305)  评论(0编辑  收藏  举报