2019.9.01 operator overloading

C # is the most common overloaded constructor overload, a variety of methods including ToString () can be overloaded operators + - * / can also be overloaded, and today we are concerned that operator overloading.

I. Introduction

  C # allows user-defined types by using the  operator  keyword static member functions defined overloaded operators. Note must be modified by the public and must be static methods of the class . However, not all built-in operators can be overloaded, in Table 1:

Operators Overloadable of
 +、-、!、~、++、--、true、false  These can be overloaded unary operator, true and false operator must reload pairs
 +、-、*、/、%、&、|、^、<<、>>  The binary operator may reload
 ==、!=、<、>、<=、>=  Comparison operators can be overloaded, must be overloaded in pairs
 &&、||  Logical operators can not be overloaded conditions, may be used and can be overloaded & | calculated
 []  The array index operator can not be overloaded, but may be defined indexer
 ()  Conversion can not be overloaded operators, but you can define a new conversion operator (see Implicit and explicit)
 +=、-=、*=、/=、%=、&=、|=、^=、<<=、>>=  Not explicit assignment operator overloading, rewriting a single operator, such as +, -,%, when they are implicitly rewritten
 =、.、?:、->、new、is、sizeof、typeof  These operators can not be overloaded

Table 1

Second, the statement

  operator keyword is used to declare a class or operator in a structure declaration. Operator declarations may be one of the following four forms:

  • public static result-type operator unary-operator ( op-type operand )

  • public static result-type operator binary-operator ( op-type operand, op-type2 operand2 )

  • public static implicit operator conv-type-out ( conv-type-in operand )

  • public static explicit operator conv-type-out ( conv-type-in operand )

 

  Parameter Description:

  result-type: result type operator.
  unary-operator: one of the following operators: + - ~ ++ - to true to false!
  OP-type: the first (or only) type parameters.
  operand: name of the first (or only) parameter.
  binary-operator: wherein a: + - * /% & | ^ == >> << => <> = <=!
  OP-Type2: the second parameter.
  operand2: name of the second parameter.
  conv-type-out: type conversion of certain types of operator.
  conv-type-in: type conversion operator input type.

  note:

  1, operator overloading declaration ways: operator keyword tells the compiler, it is actually an operator overloading, followed by a symbol associated operator.

  2, the operator can use the value of the parameter can not be used ref or out parameters. An example may refer to the notes.

  3, the first two declare a user defined built-in operators overloaded operators. op-type op-type2, and in that at least one must be a closed type (i.e. type of operator belongs to, or understood as a custom type). For example, this would prevent redefine an integer addition operator. May refer to the notes two instances.

  4, the two forms declared conversion operators. conv-type-in ​​and conv-type-out of exactly one type must be closed (i.e. conversion operator can type converted from its closed to some other type, or from some other type of closure for its type ).

  5, for the binary operators, the first parameter is the operator on the left side of the operator values, generally designated LHS; second parameter is the value on the right side of the operator, generally designated rhs.

  6, C # requires all operator overloads are declared public and static , the method must be a static class, which means that they are associated with their classes or structures, not associated with the instance .

 

Copy the code
    Student class public 
    { 
        public int Age {GET; SET;} 
        public String the Name {GET; SET;} 

        public Student () 
        {} 

        public Student (int Age, String name) 
        { 
            ; = Age this.Age 
            this.name = name; 
        } 
                
        // syntax errors: ref and out parameters invalid (ref and out keywords can be removed) in this context. 
        public static Student operator + (ref Student STU1, Student STU2 out) 
        { 
            return new new Student (stu1.Age + STU2 .Age, stu1.Name + "+++" + stu2.Name); 
        } 
    }
Copy the code
Copy the code
    Student class public 
    { 
        public int Age {GET; SET;} 
        public String the Name {GET; SET;} 

        public Student () 
        {} 

        public Student (int Age, String name) 
        { 
            ; = Age this.Age 
            this.name = name; 
        } 

        // compile error: one of the parameters of a binary operator must type comprising (parameters c1, c2, there can be a type of Student). 
        public static Student operator + (int C1, C2 int) 
        { 
            return new new Student ( c1 + c2, "Xiao novice"); 
        } 
    }
Copy the code

  

Comparison operator overloading:

  A, C # requires paired overloaded comparison operators , if overloaded == must also be overloaded! =, Or it will cause compile errors.

  B, comparison operators must return a value of type bool , which is the fundamental difference with the other arithmetic operator.

  c, in the overloaded == and! = Time, should the overload inherited from System.Object Equals () and GetHashCode () method, or it will cause a compiler warnings, because the method Equals == operator should perform the same logical equivalent.

  d, C # allowed overloaded = operator, for example, if overloaded + operator, the compiler will automatically use the operator performs overloaded + + operator = operator.

  e, any of the previous operator declaration can have an optional attribute (C # Programming Guide) list.

Key:

  Operator overloading in fact, function overloading. First operation expression specified by the corresponding operator function call, then the operands into the operator function arguments, then determining overloaded function needs to be called according to the type of arguments, the process by the compiler carry out.

Copy the code
public class UserController : Controller
    {
        public ActionResult Index()
        {
            Student student = new Student(18, "博客园");
            var resultOne = student + 3;
            var resultTwo = student + "晓菜鸟";
            return View();
        }
    }

    public class Student
    {
        public int Age { get; set; }
        public string Name { get; set; }

        public Student()
        { }

        public Student(int age, string name)
        {
            this.Age = age;
            this.Name = name;
        }          
     
        public static Student operator +(Student stu, int c2)
        {
            return new Student(stu.Age + c2, stu.Name + "-晓菜鸟");
        }

        public static Student operator +(Student stu, string suffix)
        {
            return new Student(stu.Age + 11, stu.Name + suffix);
        }   
    }
Copy the code

 

Third, examples

Copy the code
    public class UserController : Controller
    {
        public ActionResult Index()
        {
            string message = string.Empty;
            Student stuA = new Student(1, 18, "晓菜鸟");
            Student stuB = new Student(2, 21, "博客园");
            Student stuC = new Student(1, 23, "攻城狮");
            message = stuA.Name + (stuA == stuC ? "是" : "不是") + stuC.Name + "<br />";
            message += stuA.Name + (stuA != stuB ? "不是" : "是") + stuB.Name + "<br />";
            message += stuA;
            ViewData.Model = message;
            return View();
        }
    }

    public class Student
    {
        {int Id GET public; SET;} 
        public int Age {GET; SET;} 
        public String the Name {GET; SET;} 

        public Student () 
        {} 

        public Student (ID int, int Age, String name) 
        { 
            this.id = ID; 
            this.Age = Age; 
            this.name = name; 
        } 

        // overloaded ToString (), custom formatted output. 
        public String the override the ToString () 
        { 
            return "ID:" + Id + "; name:" + name + "; Age:" Age +; 
        } 
    } 

    public class Teacher 
    { 
        public int Id {GET; SET;} 

        public {GET String name; SET;}

        Strokes of Our {int GET public; SET;} 

        . // overloaded operators "+", the sum of calculating the age of the students two 
        public static Student operator + (Student LHS, RHS Student) 
        { 
            return new new Student (0, + lhs.Age rhs.Age, lhs.Name + "and" + rhs.Name); 
        } 

        // operator overloading, "-", two students calculated age difference. 
        public static operator student - (student LHS, RHS student) 
        { 
            return new student (0, Math.Abs (lhs.Age - rhs.Age), lhs.Name + " and" + rhs.Name); 
        } 

        // == operator overloading, the same default Id students the same person. 
        BOOL operator == static public (Student LHS, RHS Student) 
        { 
            return lhs.Id == rhs.Id; 
        }
 
        // comparison operators must be paired overloaded.
        public static bool operator !=(Student lhs, Student rhs)
        {
            return !(lhs == rhs);
        }
    }
Copy the code

 

  Compiler "operator overloading instance a" will produce an error, an error message: One of the parameters of a binary operator must be contained type. Here's wrong with us above the "Precautions second instance of" error or less the same as in the Teacher class, he did not know what the Student is only Student know. Only Student can decide if he can not "+ -" and not allow others to decide. operator + corresponds to a function, we can to understand, operator + (op-type operand, op-type2 operand2) equal to the op-type.operator + (operand, operand2) or op-type2.operator + (operand, operand2) .

  Examples of the dicarboxylic operator overloading

 

  "Operator Overloading Examples II" is no problem, this time we want a problem, such as our Teacher class teachers are also concerned with finding the sum and difference of age how to do? Is it only rewrite it? I wonder if you have any good ideas and insights, might leave your opinion in the comments inside! Please exhibitions, Xiao rookie greatly appreciated!

 

  I think here is inherited, but let subclasses to inherit the parent class's overloaded! See "Three examples of operator overloading."

 

Copy the code
    the UserController class public: the Controller 
    { 
        public ActionResult Index () 
        { 
            String Message = string.Empty; 
            Teacher Teacher TEAA new new = (. 11, 30, "Director Liu", "teaches director"); 
            Teacher TEAB = new new Teacher (12 is, 45 "Lu teacher", "assistant principal"); 
            teacher Teac = new new teacher (11, 27, "Liu", "small second class teacher"); 
            Student stuOne = new new Student (1, 18, "Xiao rookie") ; 
            Student stuTwo = new new Student (2, 21, "blog garden"); 
            Student stuThree = new new Student (1, 23, "siege lion"); 
            ? = stuOne.Name the Message + (stuOne == stuThree "Yes": "No") + stuThree.Name + "<br /> ";
            message + = stuOne.Name + (!? stuOne = stuTwo " not": "Yes") + + stuTwo.Name "<br />"; 
            the this.Age = age;
            message + = string.Format ( "{0 } and {1} Age sum is: {2} <br />", stuOne.Name, stuThree.Name, stuOne stuThree +); 
            Message = + string.Format ( " Age {0} and {1} is the difference between: <br /> {2} ", stuOne.Name, stuTwo.Name, stuOne - stuTwo); 
            Message = + stuOne; 
            the ViewData.Model = Message; 
            return View (); 
        } 
    } 

    public class Student: People 
    { 
        public Student () 
        {} 

        public Student (ID int, int Age, String name) 
        { 
            this.id ID =; 
            this.name = name; 
        } 

        // overloaded ToString (), custom formatted output. 
        public String the override the ToString () 
        { 
            return "ID:" + Id + "; Name:" + Name + "; Age:" Age +; 
        } 
    } 

    public class Teacher: People 
    { 
        /// <Summary> Position </ summary> 
        Strokes of Our GET String {public; SET;} 

        public Teacher () {} 

        public Teacher (ID int, int Age, String name, String Duties) 
        { 
            this.id ID =; 
            this.Age = Age; 
            this.name = name; 
            the this Duties = .Duties; 
        } 
    } 

    // abstract: abstract class is used as the base class can not be instantiated, other uses are derived non-abstract class. 
    public abstract class People 
    {
        {int Id GET public; SET;} 
        public int Age {GET; SET;} 
        public String the Name {GET; SET;} 

        // overloaded operators "+", calculates the sum of age. 
        public static int operator + (LHS People, RHS People) 
        { 
            return lhs.Age + rhs.Age; 
        } 

        // operator overloading, "-", age difference is calculated. 
        public static int operator - (People LHS, RHS People) 
        { 
            return the Math.Abs (lhs.Age - rhs.Age); 
        } 

        // == operator overloading, the same Id are considered equal. 
        public static BOOL operator == (People LHS, RHS People) 
        { 
            return lhs.Id == rhs.Id; 
        } 

        // comparison overload operator must be paired. 
        public static BOOL operator = (People LHS, RHS People! ) 
        {
            return !(lhs == rhs);
        }
    }
Copy the code

 

 

 

"Operator Overloading Example III" Run Results FIG:

FIG example operator overloading 

Guess you like

Origin www.cnblogs.com/LiTZen/p/11444257.html