C# 运算符重载简介

C#运算符重载

重载运算符是具有特殊名称的函数,是通过关键字 operator 后跟运算符的符号来定义的。与其他函数一样,重载运算符有返回类型和参数列表。

//格式:
//修饰符 返回值类型 operator 可重载的运算符(参数列表)
public static Student operator +(Student a, Student b)
{
    //方法体;
} 

运算符重载的其实就是函数重载。首先通过指定的运算表达式调用对应的运算符函数,然后再将运算对象转化为运算符函数的实参,接着根据实参的类型来确定需要调用的函数的重载,这个过程是由编译器完成。

可重载和不可重载运算符

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

C# 要求成对重载比较运算符。如果重载了==,则也必须重载!=,否则产生编译错误。同时,比较运算符必须返回bool类型的值,这是与其他算术运算符的根本区别。


下面以重载“+”运算符,为例:(重载“+”编译器会自动重载“+=”);

using System;

namespace _6_2_1运算符重载
{
    class Program
    {
        static void Main(string[] args)
        {
            Student st1 = new Student();
            Student st2 = new Student();
            Student st3 = new Student();

            st1._acore = 40;
            st2._acore = 50;

            Console.WriteLine("st1和st2成绩是否相同:" + (st1 == st2));
            Console.WriteLine("st1和st2成绩是否相同:" + (st1 != st2));

            Console.WriteLine("运算前成绩:{0},{1},{2}", st1._acore, st2._acore, st3._acore);

            //对象相加
            st3 = st1 + st2;
            //编译器自动重载+=
            st1 += st2;

            Console.WriteLine("运算后成绩:{0},{1},{2}",st1._acore,st2._acore,st3._acore);




            Console.ReadKey();
        }


    }

    class Student
    {
        private int acore;

        public int _acore {
            get { return acore; }
            set { acore = value; }
        }

        //+重载: 对象加法,求得学生成绩和
        public static Student operator +(Student b, Student c)
        {
            Student stu = new Student();
            stu.acore = b.acore + c.acore;

            return stu;
        }

        //当重载==时,必须重载!=,否则编译报错
        public static bool operator ==(Student b , Student c)
        {
            bool result = false;
            if(b.acore == c.acore)
            {
                result = true;
            }
            return result;
        }

        public static bool operator !=(Student b, Student c)
        {
            bool result = false;
            if (b.acore != c.acore)
            {
                result = true;
            }
            return result;
        }


    }
}

输出结果:

猜你喜欢

转载自blog.csdn.net/czhenya/article/details/80151862