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);
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值