【C#】类_封装_运算符重载

类_封装_运算符重载

基本概念:让自定义的类和结构体能够使用运算符进行运算。

语法:关键词 operator

public static 返回类型 operator 运算符(参数列表)

特点

  1. 公共静态方法;
  2. 返回值写在operator前;
  3. 逻辑处理自定义;
  4. 条件运算符需要成对出现,即有>运算符重载,相应就一定要有<运算符重载;一个符号可以多个重载;不能使用ref和out。

可重载与不可重载的运算符

算数运算符——>+ 二元运算符只能有两个参数;

不可重载的运算符:

  • 逻辑与(&&)、逻辑或(||)
  • 索引符[ ]
  • 强转运算符( )
  • 特殊运算符: 点. 三元运算符 ? : 赋值运算符

实例

    class Point
    {
        public int x; 
        public int y; 

        public static Point operator +(Point p1,Point p2)
        {
            Point p = new Point();
            p.x = p1.x + p2.x;
            p.y = p1.y + p2.y;
            return p;
        }

        public static Point operator +(Point p1, int value)
        {
            Point p = new Point();
            p.x = p1.x + value;
            p.y = p1.y + value;
            return p;
        }
    }

练习题

namespace L10_封装_运算符重载
{
    //练习题一
    //定义一个位置结构体或类,为其重载判断是否相等的运算符
    //(x1,y1) == (x2,y2) =>两个值同时相等才为true
    class Location
    {
        public int x;
        public int y;

        public static bool operator ==(Location l1,Location l2)
        {
                return l1.x == l2.x && l1.y == l2.y;
        }

        public static bool operator !=(Location l1, Location l2)
        {
            return l1.x != l2.x || l1.y != l2.y;

        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            //练习题一:
            Location l1 =new Location();
            l1.x = 1;
            l1.y = 2;
            Location l2 =new Location();
            l2.x = 1;
            l2.y = 2;
            if (l1 == l2) { Console.WriteLine("l1和l2两个值相等"); }
            else { Console.WriteLine("l1和l2两个值不等"); }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值