C# 运算符重载

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 on 2016-10-03 12:27 时空观察者9号 阅读(...) 评论(...) 编辑 收藏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值