面向对象----C#运算符重载

什么是运算符重载?

                重载是面向对象中的一个重载概念,它是对象多态性的一种不完全体现。所谓运算符重载,就是对已有的运算符重新定义,赋予其另一种功能,以适应不同的数据类型。

为什么要需要运算符重载?

      比如:
        1+1=2                        这是系统默认可以识别并可以运算的
        1杯水+1杯水=2杯水    这时系统就无法判断你要做什么。
        此时就需要重新定义“+”运算符就可以实现生活中各种对象之间“和”的运算。

运算符重载格式

       访问修饰权限 +数据类型+关键字(operator)+运算符+(形参表)
     {
           函数体 ;
      }

运算符重载实例

        
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication14
{
    class Program
    {
        public static void Main(string[] args)
        {
            Vector vect1, vect2, vect3;
            vect1 = new Vector(3.0, 3.0, 1.0);  //调用运算符函数
            vect2 = new Vector(2.0, -4.0, -4.0);
            vect3 = vect1 + vect2;              //实现运算符重载
            Console.WriteLine(vect1.ToString());
            Console.WriteLine(vect2.ToString());
            Console.WriteLine( vect3.ToString());
        }
      
        class Vector
        {
            private double x, y, z;
            public double X
            {
                get { return x; }
                set { y = value; }
            }
            public double Y
            {
                get { return y; }
                set { y = value; }
            }
            public double Z
            {
                get { return z; }
                set { z = value; }
            }
            public Vector()
            {
                x = 0;
                y = 0;
                z = 0;
            }
            public Vector(Vector rhs)
            {
                x = rhs.x;
                y = rhs.y;
                z = rhs.z;
            }
            public Vector(double x, double y, double z)
            { 
                this .x=x ;
                this .y=y;
                this.z=z;
            }
            public override string ToString()   
            {
                return "X的坐标是:"+x+"Y的坐标是:"+y+"Y的坐标是:"+z ;
            }
            public static Vector operator +(Vector lhs, Vector rhs)     //声明运算符重载
            {
                Vector result = new Vector(lhs);
                result.x += rhs.x;
                result.y += rhs.y;
                result.z += rhs.z;
                return result;
            }
        }
        
    }
}
      运行的结果如下 
               
   不同的运算符中重载时有不同的要求
         
                
              
  • 8
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 24
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值