zoukankan      html  css  js  c++  java
  • 运算符重载

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

        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();
            }
  • 相关阅读:
    给目录下所有文件与文件夹加权限
    应用程序无法正常启动0xc000007b解决方法
    文件关联修复方法
    xz压缩文件方法
    sharding-jdbc实现水平分库 + 水平分表
    Sharding-jdbc实现水平分表
    批量删除Maven本地仓库中未下载完成的jar包(不完整的jar包)
    分库分表
    尚硅谷 ShardingSphere
    SpringBoot 整合ActiveMQ
  • 原文地址:https://www.cnblogs.com/mq0036/p/4008644.html
Copyright © 2011-2022 走看看