概念
运算符也称操作符,是指+,-,*等,代表了一定的运算。
运算符的声明方式:
- 一元运算符
public static 类型 operator 一元运算符(类型 参数名){…}
如:public static Complex operator +(Complex c1){…}- 二元运算符
public static 类型 operator 二元运算符(类型 参数名,类型 参数名){…}
如:public static Complex operator * (Complex1 c1, Complex2 c2){…}- 转换运算符
运算符重载的一些限制
- 运算符的参数不能用ref / out修饰。
- 不能改变运算符的优先级;
- 不能改变一个运算符需要的操作数的个数,即使可以忽略某一个操作数。
- 有些运算符不能重载:=、+=、成员访问、方法调用或=、&&、||、?:、new、typeof、sizeof、is;
- 比较运算符如果被重载,必须成对重载;也就是说:
– 如果重载了==,必须重载!=。
– 如果重载了<,必须重载>。
一元运算符
- 运算符 + - * ÷
例如:复数求相反数。
public class Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator -(Complex c1)
{
return new Complex(-c.real, -c.imaginary)
}
}
- 运算符 ++ –
用来移动一个点,使其横纵坐标都+1
public class Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public static Point operator ++ (Point p)
{
p.x++; p.y++;
return p;
}
}
二元运算符
可重载的二元运算符包括:+ - * % & | ^ << >> == != > < >= <=
必须遵循以下规则:
- 必须有两个参数,至少一个是声明运算符的类或结构的类型。一个二元运算符可以返回任何种类的类型。
- 成对声明: ==和!=,>和< ,<=和>=
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _0902_运算符重载
{
public class 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 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 new Complex(c1.real - c2.real, c1.imaginary - c2.imaginary);
}
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 c1, double k)
{
return new Complex(c1.real * k, c1.imaginary * k);
}
public static Complex operator *(double k, Complex c1)
{
return c1*k;
}
public override string ToString()
{
return (String.Format("({0},{1})", real, imaginary));
}
}
class Program
{
static void Main(string[] args)
{
var c1 = new Complex(1.0, 2.0);
var c2 = new Complex(9.0, 4.0);
Console.WriteLine((c1*c2).ToString());
}
}
}