C# 运算符重载

C#运算符重载函数必须是public static

    struct CSTest
    {
        public int posx;
        public static CSTest operator + (CSTest o1, CSTest o2)
        {//二元运算符重载
            CSTest ost = new CSTest();
            ost.posx = o1.posx + o2.posx;
            return ost;
        }
        public static CSTest operator - (CSTest ot)
        {//一元运算符重载
            ot.posx = -ot.posx;
            return ot;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CSTest ostn1 = new CSTest();
            CSTest ostn2 = new CSTest();
            ostn1.posx = 1;
            ostn2.posx = 2;
            CSTest ostn3 = ostn1 + ostn2;
            ostn3 = -ostn3;
            Console.WriteLine(ostn3.posx);
        }
    }

C++可以对[]进行重载,而C#不可以对方括号重载但是提供了索引器的语法。

可重载和不可重载运算符

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

运算符描述
+, -, !, ~, ++, -- 这些一元运算符只有一个操作数,且可以被重载。
+, -, *, /, % 这些二元运算符带有两个操作数,且可以被重载。
==, !=, <, >, <=, >= 这些比较运算符可以被重载。
&&, || 这些条件逻辑运算符不能被直接重载。
+=, -=, *=, /=, %= 这些赋值运算符不能被重载。
=, ., ?:, ->, new, is, sizeof, typeof 这些运算符不能被重载。
posted @ 2016-10-03 12:27  时空观察者9号  阅读(395)  评论(0编辑  收藏  举报