首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 運算子多載實作指南:Complex 類別重載 +、- 運算子完整程式碼

     編輯:關於C語言

運算子多載語法

格式:public static 回傳型別 operator 運算子(參數列表)。所有多載皆為 static 方法。若多載 == 必須同時多載 !=。

可多載運算子

  • 一元:+ - ! ~ ++ -- true false
  • 二元:+ - * / % & | ^ << >> == != > < >= <=

Complex 類別完整程式碼


using System;

public class complex
{
    private float real;
    private float img;

    public complex(float p, float q) { real = p; img = q; }
    public complex() { real = 0; img = 0; }

    public void Print() => Console.WriteLine("{0} + {1}i", real, img);

    // 多載 +
    public static complex operator +(complex lhs, complex rhs)
    {
        complex sum = new complex();
        sum.real = lhs.real + rhs.real;
        sum.img = lhs.img + rhs.img;
        return sum;
    }

    // 多載 -
    public static complex operator -(complex lhs, complex rhs)
    {
        complex result = new complex();
        result.real = lhs.real - rhs.real;
        result.img = lhs.img - rhs.img;
        return result;
    }
}

此類別示範如何讓自訂型別支援直觀的算術運算子。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved