zoukankan      html  css  js  c++  java
  • 如何:使用运算符重载创建复数类

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

     1public struct Complex
     2{
     3    public int real;
     4    public int imaginary;
     5
     6    public Complex(int real, int imaginary)  //constructor
     7    {
     8        this.real = real;
     9        this.imaginary = imaginary;
    10    }

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

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

    25}

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

    42}
    输出 :
    First complex number:  2 + 3i
    Second complex number: 3 + 4i
    The sum of the two numbers: 5 + 7i
  • 相关阅读:
    mysql limit
    random.nextint()
    “MSDTC 事务的导入失败: Result Code = 0x8004d00e。
    JUnit-4.11使用报java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing错误
    iOS ERROR: unable to get the receiver data from the DB 解决方式
    STL algorithm算法mov,move_backward(38)
    看 《一次谷歌面试趣事》 后感
    C++胜者树
    拿年终奖前跳槽,你才是赢家!
    日期字符串格式化成日期/日期格式化成指定格式字符串
  • 原文地址:https://www.cnblogs.com/qixin622/p/602234.html
Copyright © 2011-2022 走看看