码迷,mamicode.com
首页 > 其他好文 > 详细

运算符重载

时间:2014-10-06 22:08:50      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   sp   div   c   on   log   

最近学校学了运算符重载,虽然很简单,还是记录下,以便于以后忘记和学习。

    class XS
    {
        private double RP;         //实部
        private double IP;         //虚部
        public double getRP
        {
            get { return RP; }
        }
        public double getIP
        {
            get { return IP; }
        }

        public XS()  //构造函数
        {
            RP = IP = 0;
        }
        public XS(double RP, double IP)//构造函数重载
        {
            this.RP = RP;
            this.IP = IP;

        }

        //加号+重载
        public static XS operator +(XS c1, XS c2)
        {
            XS c = new XS(c1.RP + c2.RP, c1.IP + c2.IP);
            return c;
        }

        //对取反符号-重载(一元运算符重载)
        public static XS operator -(XS c)
        {
            XS c2 = new XS(-c.RP, -c.IP);
            return c2;
        }

        //对减号-重载(二元运算符重载)
        public static XS operator -(XS c1, XS c2)
        {
            XS c = new XS(c1.RP - c2.RP, c1.IP - c2.IP);
            return c;
        }

        //实现隐式类型转换(从 string 到 XS)
        public static implicit operator XS(string s)
        {
            s = s.Trim().TrimEnd(i);
            s = s.Trim().TrimEnd(*);
            string[] digits = s.Split(+, -);
            XS c;
            c = new XS(Convert.ToDouble(digits[0]), Convert.ToDouble(digits[1]));
            return c;
        }

        //输出虚数
        public void putOut()
        {
            Console.WriteLine("{0} + {1}*i", RP, IP);
        }
    }

static void Main(string[] args)
        {
            //调用不带参数的构造函数创建虚数对象c1
            XS c1 = new XS();
            //调用带参数的构造函数创建虚数对象c2
            XS c2 = new XS(1, 2);
            Console.Write("c1 = "); c1.putOut();
            Console.Write("c2 = "); c2.putOut();
            XS c3;
            c3 = "100+200*i";                 // 通过隐式转换对c3赋值
            Console.Write("c3 = "); c3.putOut();
            XS c4;
            c4 = -c2 - c1 + c3;                //对对象进行加减运算
            Console.Write("c4 = "); c4.putOut();
            Console.ReadKey();
        }

 

运算符重载

标签:style   blog   color   ar   sp   div   c   on   log   

原文地址:http://www.cnblogs.com/mq0036/p/4008644.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!