您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關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#中怎么通過運算符重載實現復數運算有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。