学习C#运算符重载

C#运算符重载

以下均为在菜鸟教程中学习的笔记


你可以重定义或重载C#中内置的运算符。程序员可以使用用户自定义类型的运算符。

重载运算符是具有特殊名称的函数,是通过关键字operator后跟运算符的符号来定义的。

与其他函数一样,重载运算符有返回类型和参数列表。

运算符重载的实现

实例:

class Box
    {
        //重载+运算符来把两个Box对象相加
        public static Box operator +(Box b, Box c)
        {
            Box box = new Box();
            box.length = b.length + c.length;
            return box;
        }
        private double length;
        public double getLength()
        {
            return length ;
        }
        public void setLength(double len)
        {
            length = len;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Box box1 = new Box();//声明box1,类型为Box
            Box box2 = new Box();//声明box2,类型为Box
            Box box3 = new Box();//声明box3,类型为Box
            double volume = 0.0;
            //box1
            box1.setLength(6.0);
            //box2
            box2.setLength(12.0);
            //box1的长度
            volume = box1.getLength();
            Console.WriteLine("box1的长度:{0}", volume);
            //box2的长度
            volume = box2.getLength();
            Console.WriteLine("box2的长度:{0}", volume);
            //把两个对象相加
            box3 = box1 + box2;
            //box3的长度
            volume = box3.getLength();
            Console.WriteLine("box3的长度:{0}", volume);
            Console.ReadLine();
        }
    }

结果:

box1的长度:6
box2的长度:12
box3的长度:18

可重载和不可重载运算符

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

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

个别实例:

public static bool operator == (Box lhs, Box rhs)
      {
          bool status = false;
          if (lhs.length == rhs.length && lhs.height == rhs.height
             && lhs.breadth == rhs.breadth)
          {
              status = true;
          }
          return status;
      }

猜你喜欢

转载自www.cnblogs.com/wei1349/p/12901050.html