C#学习-运算符重载(operator)

运算符重载意义:

使某些运算符具有新的功能

重载的前提:

方法必须是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
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早日退休过上不劳而获生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值