C#中怎么通过运算符重载实现复数运算
短信预约 -IT技能 免费直播动态提醒
今天就跟大家聊聊有关C#中怎么通过运算符重载实现复数运算,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
C#运算符重载实现复数运算的由来:函数的重载——同名函数,不同的参数(包括参数个数不同和参数个数相同但个数不同)
将其引申,像如下的代码:
int i=5; int j=2; int sum=i+j;
如果没有自定义的C#运算符重载,像+,-,*,/这样的运算符只能用于预定义的数据类型,编译器认为所有常见的运算符都是用于这些数据类型的。
问题来了,如果我要对两个复数或矩阵进行四则运算,就需要我们自己扩展运算符重载函数了。
C#运算符重载之示例:复数的四则运算
public struct Complex { public int real; public int imaginary; public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } //overload operator(+),added(two Complex objects) and return a Complex type public static Complex operator +(Complex c1, Complex c2) { return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary); } //overload operator(-) public static Complex operator -(Complex c1, Complex c2) { return new Complex(c1.real - c2.real, c1.imaginary - c2.imaginary); } //overload operator(*) public static Complex operator *(Complex c1, Complex c2) { return new Complex(c1.real * c2.real - c1.imaginary * c2.imaginary, c1.real * c2.imaginary + c1.imaginary * c2.real); } //overload operator(/) public static Complex operator /(Complex c1, Complex c2) { return new Complex(-c1.real * c2.real + c1.imaginary * c2.imaginary, -c1.real * c2.imaginary + c1.imaginary * c2.real); } // Override the ToString method to display an complex number in the suitable format: public override string ToString() { return (String.Format("{0} + {1}i", real, imaginary)); } }
C#运算符重载之客户端代码:
static void Main(string[] args) { Complex num1 = new Complex(2, 3); Complex num2 = new Complex(3, 4); //Add two Complex objects (num1 and num2) through the overloaded plus operator: Complex sum_Add = num1 + num2; Complex sum_Minus = num1 - num2; Complex sum_Product = num1 * num2; Complex sum_Divide = num1 / num2; //Print the numbers and the Result using the overriden ToString method: Console.WriteLine("First complex number: {0}", num1); Console.WriteLine("Second complex number: {0}", num2); Console.WriteLine("The sum of the two numbers: {0}", sum_Add); Console.WriteLine("The Minus of the two numbers: {0}", sum_Minus); Console.WriteLine("The Product of the two numbers: {0}", sum_Product); Console.WriteLine("The Divide of the two numbers: {0}", sum_Divide); Console.ReadLine(); }
C#运算符重载实例运行结果:
First complex number: 2 + 3i Second complex number: 3 + 4i The sum of the two numbers: 5 + 7i The Minus of the two numbers: -1 + -1i The Product of the two numbers: -6 + 17i The Divide of the two numbers: 6 + 1i
看完上述内容,你们对C#中怎么通过运算符重载实现复数运算有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网行业资讯频道,感谢大家的支持。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341