C#学习笔记 运算符重载

运算符(operator)也称操作符,是指+-*等,C#中允许对用户定义的类型重新定义各种运算符的意义,这就是运算符重载(operator overloading)。
比如,两个日期时间(DateTime)相减,表示两个日期的时间间隔(TimeSpan);而日期时间加上一个时间间隔则得到另一个日期时间:

	DateTime now = DateTime.Now;
	DateTime start = new DateTime(2000, 1, 1);
	TimeSpan c = now - start;
	Console.WriteLine(c.TotalDays);

事实上,在这里时间相减的运算符(即减号),就是一个调用了“op_Subtraction”这个特殊的方法,在.NET framework的API文档中,DateTimeOperators(运算符)中将这个运算符叫作op_Subtraction

示例: 自定义运算符重载计算复数。

using System;

public struct Complex
{
    
    
	public double real;
	public double imaginary;
	public Complex(double real, double imaginary) {
    
    
		this.real = real;
		this.imaginary = imaginary;
	}
	// 单元运算
	public static Complex operator +(Complex c1) {
    
     return c1; }
	public static Complex operator -(Complex c1) {
    
     return new Complex(-c1.real, -c1.imaginary); }
	public static bool operator true(Complex c1) {
    
     return c1.real != 0 || c1.imaginary != 0; }
	public static bool operator false(Complex c1) {
    
     return c1.real == 0 && c1.imaginary == 0; }

	// 双元运算
	public static Complex operator +(Complex c1, Complex c2) {
    
     return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary); }
	public static Complex operator -(Complex c1, Complex c2) {
    
     return c1 + (-c2); }
	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);
	}
	public static Complex operator *(Complex c, double k) {
    
     return new Complex(c.real * k, c.imaginary * k); }
	public static Complex operator *(double k, Complex c) {
    
     return c * k; }

	public override string ToString() {
    
    
		return (System.String.Format("({0} + {1}i)", real, imaginary));
	}
}

static void Main(string[] args) {
    
    
	Console.WriteLine("Hello World!");

	Complex num1 = new Complex(2, 3);
	Complex num2 = new Complex(3, 4);

	Complex result = num1 ? -num1 * 5 + num1 * num2 : new Complex(0, 0);

	Console.WriteLine("First complex number:  {0}", num1);
	Console.WriteLine("Second complex number: {0}", num2);
	Console.WriteLine("The result is: {0}", result);
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45349225/article/details/114156151