运算符重载意义:
使某些运算符具有新的功能
重载的前提:
方法必须是public和static
注意:
参数类型和返回值类型可以随意设置,但要合法
可重载的运算符:
- 算术运算符:全部,eg:+、-、*、/、++、--
- 赋值运算符:全部不可
- 关系运算符:全部,但必须要成对重载。eg:“<”要和“>”一起
- 逻辑运算符:部分可以部分不行。eg:&、|、!、^可以,&&、||不行
- 位运算符:~可以
代码理解:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2020cexample
{
public struct Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
//运算符重载,使得+具有新的功能
//可以使两个Point对象直接相加,得到一个新的点
//前提方法必须是public和static
public static Point operator +(Point p1,Point p2){
return new Point(p1. x + p2.x, p1.y + p2.y);
}
//参数类型和返回值类型可以随意设置,但要合法
public static int operator +(Point p, int a)
{
return p.x+a;
}
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point(1,2);
Point p2 = new Point(3,4);
Point p3 = p1+ p2;
Console.WriteLine(p3.x);//4
Console.WriteLine(p3.y );//6
Console.WriteLine(p1+2);//3
}
}
}