• 操作符重载


    C#中,下列操作符可以重载:
    + - ! ~ ++ 00 true false
    * / % & | ^ << >> == != > < >= <=
    下列操作符是不允许进行重载的:
    = && || ?: new typeof sizeof is

    // 操作符重载演示
    using System;
    class Player
    {
        public int neili;
        public int tili;
        public int jingyan;
        public int neili_r;
        public int tili_r;
        public Player()
        {
            neili = 10;
            tili = 50;
            jingyan = 0;
            neili_r = 50;
            tili_r = 50;
        }
       
        // 一元操作符重载
        public static Player operator ++(Player p)
        {
            p.neili = p.neili + 50;
            p.tili = p.tili + 50;
            p.neili_r = p.neili;
            p.tili_r = p.tili;
            return p;
        }
       
        // 二元操作符重载
        public static Player operator +(Player p1, Player p2)
        {
            Player p = new Player();
            p.neili = p1.neili +p2.neili;
            p.tili = p1.tili + p2.tili;
            p.neili_r = p.neili;
            p.tili_r = p.tili;
           
            return p;
        }
       
        public static void Main()
        {
            Player p1 = new Player();
            Player p2 = new Player();
            p1++;
            Console.WriteLine(" {0}", p1.neili);
           
            Player p = p1 + p2;
            Console.WriteLine(" {0}", p.neili);
        }
    }
  • 相关阅读:
    1001.A+B for Matrices
    1016.火星A+B
    1468.Sharing
    1464.Hello World For U
    约瑟夫问题pascal程序
    约数研究pascal程序
    迷宫pascal程序
    魔法照片pascal程序
    均分纸牌pascal程序
    多项式输出pascal程序
  • 原文地址:https://www.cnblogs.com/netfork/p/3860.html
Copyright © 2020-2023  润新知