运算符重载
最近学校学了运算符重载,虽然很简单,还是记录下,以便于以后忘记和学习。
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(); }
关注我】。(●'◡'●)
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的【因为,我的写作热情也离不开您的肯定与支持,感谢您的阅读,我是【Jack_孟】!
本文来自博客园,作者:jack_Meng,转载请注明原文链接:https://www.cnblogs.com/mq0036/p/4008644.html
【免责声明】本文来自源于网络,如涉及版权或侵权问题,请及时联系我们,我们将第一时间删除或更改!