C#运算符重载

运算符重载:通过特定的语法,是某些运算符可以具备特殊的功能。关键字operator,修饰符必须为public static。
【注意事项】
1、参数的数量一定要和这个运算符操作的数量匹配。
2、参数类型和返回值类型可以随意设置,但要合情合理。
3、可以重载的运算符有:算术运算符(+、-、*、/、++、–)、关系运算符(>、<、>=、<=、==、!=)、逻辑运算符(&、|、!、^)、位运算符(~)。
4、关系运算符如果想重载,那么必须要成对的重载,例如:重载了>,则必须重载<。
5、不可被重载的运算符有:赋值运算符、逻辑运算符中的(&&、||)。

重写语法代码如下:

using System;

public  struct Point
{
    public double x;
    public double y;
    public Point(double x,double y)
    {
        this.x = x;
        this.y = y;
    }
//运算符重载,使加号具有新的功能
//可以实现两个Point对象直接相加,得到一个新的点
    public static Point operator +(Point p1,Point p2)
    {
        return new Point(p1.x + p2.x, p1.y + p2.y);
    }
    //参数类型可以不相同
    public static Point operator + (Point p1,int a)
    {
        return new Point(p1.x + a, p1.y + a);
    }
//*号是二元运算符,因此必须有两个参数
    public static Point operator *(Point p1,Point p2)
    {
        return new Point(1, 1);
    }
//-号的身份有两种:1是加减乘除的减号,2是负号。为前者时是二元运算符,为后者是一元运算符。
    public static Point operator - (Point p1)
    {
        return new Point(1, 1);
    }
    //【重载--运算符】练习
    public static Point operator --(Point p1)
    {
        return new Point(p1.x-1,p1.y-1);
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Point p1 = new Point(1, 2);
        Point p2 = new Point(2, 3);
        Point p = p1 + p2;
        //【重载--运算符】练习
        Point p3 = new Point(1, 3);
        p3--;
        Console.WriteLine(p3.x);
        Console.WriteLine(p3.x);
        Console.WriteLine(p3.y);
        p3 = new Point(1, 3);
        --p3;
        Console.WriteLine(p3.x);
        Console.WriteLine(p3.y);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值