C# 运算符重载

C#中允许重定义或重载内置运算符。因此程序员可以使使用用户自定义类型的运算符。重载运算符具有特殊名称的函数,是通过关键字operator后跟运算符的符号来定义的。与其他函数一样,重载运算符有返回类型和参数列表。

运算符重载的实现

//运算符重载的实现
using System;
namespace OperatorOvlApplication
{
    class Box
    {
        private double length;
        private double breadth;
        private double height;

        public double getVolume()
        {
            return length*breadth*height;
        }

        public void setLength(double l)
        {
            length = l;
        }

        public void setBreadth(double b)
        {
            breadth = b;
        }

        public void setHeight(double h)
        {
            height = h;
        }


        public static Box operator +(Box b, Box c)
        {
            Box box = new Box();
            box.length = b.length+c.length;
            box.width = b.breadth + c.breadth;
            box.height = b.height + b.height;

            return box;
        }

    }

    class Test
    {
        public static void Main(string[] args)
        {
            Box box1 = new Box();
            Box box2 = new Box();
            Box box3 = new Box();
            double volume;

            box1.setLength(3.5);
            box1.setWidth(4.0);
            box1.setHeight(8.9);

            box2.setLength(11);
            box2.setWidth(12);
            box2.setHeight(13);

            volume = box1.getVolume();
            Console.WriteLine("box1的体积是:{0}",volume);

            volume = box1.getVolume();
            Console.WriteLine("box2的体积是:{0}",volume);

            box1 = box2 + box3;

            volume = box3.getVolume();
            Console.WriteLine("box3的体积是:{0}",volume);
            Console.ReadLine();
        }
    }
}


可重载和不可重载运算符

下表描述了C#中运算符重载的能力:

运算符 描述
+, -, !, ~, ++, -- 这些一元运算符只有一个操作数,且可以被重载。
+, -, *, /, % 这些二元运算符带有两个操作数,且可以被重载。
==, !=, <, >, <=, >= 这些比较运算符可以被重载。
&&, || 这些条件逻辑运算符不能被直接重载。
+=, -=, *=, /=, %= 这些赋值运算符不能被重载。
=, ., ?:, ->, new, is, sizeof, typeof 这些运算符不能被重载。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值