如何:使用运算符重载创建复数类

本示例展示如何使用运算符重载创建定义复数加法的复数类 Complex。本程序使用 ToString 方法的重载显示数字的虚部和实部以及加法结果。

 1 None.gif public   struct  Complex
 2 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 3InBlock.gif    public int real;
 4InBlock.gif    public int imaginary;
 5InBlock.gif
 6InBlock.gif    public Complex(int real, int imaginary)  //constructor
 7ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 8InBlock.gif        this.real = real;
 9InBlock.gif        this.imaginary = imaginary;
10ExpandedSubBlockEnd.gif    }

11InBlock.gif
12InBlock.gif    // Declare which operator to overload (+),
13InBlock.gif    // the types that can be added (two Complex objects),
14InBlock.gif    // and the return type (Complex):
15InBlock.gif    public static Complex operator +(Complex c1, Complex c2)
16ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
17InBlock.gif        return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
18ExpandedSubBlockEnd.gif    }

19InBlock.gif
20InBlock.gif    // Override the ToString() method to display a complex number in the traditional format:
21InBlock.gif    public override string ToString()
22ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
23InBlock.gif        return (System.String.Format("{0} + {1}i", real, imaginary));
24ExpandedSubBlockEnd.gif    }

25ExpandedBlockEnd.gif}

26 None.gif
27 None.gif class  TestComplex
28 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
29InBlock.gif    static void Main()
30ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
31InBlock.gif        Complex num1 = new Complex(23);
32InBlock.gif        Complex num2 = new Complex(34);
33InBlock.gif
34InBlock.gif        // Add two Complex objects through the overloaded plus operator:
35InBlock.gif        Complex sum = num1 + num2;
36InBlock.gif
37InBlock.gif        // Print the numbers and the sum using the overriden ToString method:
38InBlock.gif        System.Console.WriteLine("First complex number:  {0}", num1);
39InBlock.gif        System.Console.WriteLine("Second complex number: {0}", num2);
40InBlock.gif        System.Console.WriteLine("The sum of the two numbers: {0}", sum);
41ExpandedSubBlockEnd.gif    }

42ExpandedBlockEnd.gif}
输出 :
First complex number:  2 + 3i
Second complex number: 3 + 4i
The sum of the two numbers: 5 + 7i
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值