重載運算元

1 篇文章 / 0 new
author
重載運算元
下範例程式碼為定義自己的運算元計算規則
    public struct Complex
    {
        public int real;
        public int imaginary;
        public Complex(int real, int imaginary)
        {
            this.real = real;
            this.imaginary = imaginary;
        }
        public static Complex operator +(Complex c1, Complex c2)//重載 '+' 運算元
        {
            return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
        }
        public override string ToString()//重載 toString
        {
            return (String.Format("{0} + {1}i", real, imaginary));
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Complex n1 = new Complex(1, 2);
            Complex n2 = new Complex(3, 4);
            Complex n = n1+n2;
            Console.WriteLine(n);//等同 n.ToString();
 
            Console.ReadLine();
        }
    }

注意 : 比較運算元如果重載, 成對的運算元也須一並重載, 如 == vs != , < vs > , <= vs >=
Free Web Hosting