zoukankan      html  css  js  c++  java
  • 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 这些运算符不能被重载。
  • 相关阅读:
    input 蓝边
    4.【ac自动机】模式串匹配
    3.【二叉树】最近公共祖先
    2.【动态规划】最长回文子串
    1. 【线段树】
    DbUtil
    oauth2
    cas
    Spring-security-web
    JSON Web Tokens
  • 原文地址:https://www.cnblogs.com/timeObjserver/p/5928984.html
Copyright © 2011-2022 走看看