首页 > 代码库 > 运算符重载
运算符重载
最近学校学了运算符重载,虽然很简单,还是记录下,以便于以后忘记和学习。
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(); }
运算符重载
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。