标签: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