先决条件: C中的运算符#
重载函数的概念也可以应用于 操作员 .运算符重载提供了使用同一运算符执行各种操作的能力。它为 C# 当运算符应用于用户定义的数据类型时。它允许用户定义各种操作的实现,其中一个或两个操作数属于用户定义的类。只有预定义的 C# 运算符可能会过载。对用户定义的数据类型进行操作并不像对内置数据类型进行操作那样简单。要使用具有用户定义的数据类型的运算符,需要根据程序员的要求对其进行重载。可以通过为运算符定义函数来重载运算符。通过使用 操作员关键字 .
语法:
access specifier className operator Operator_symbol (parameters){ // Code}
注: 运算符重载基本上是为理想的C#运算符w.r.t.提供特殊含义的机制。它是用户定义的数据类型,如结构或类。
下表介绍了C#中可用的各种运算符的重载能力:
操作员 | 描述 |
---|---|
+, -, !, ~, ++, – – | 一元运算符接受一个操作数,可以重载。 |
+, -, *, /, % | 二进制运算符有两个操作数,可以重载。 |
==, !=, = | 比较运算符可以重载。 |
&&, || | 条件逻辑运算符不能直接重载 |
+=, -+, *=, /=, %=, = | 不能重载赋值运算符。 |
重载一元运算符
返回类型可以是除一元运算符void之外的任何类型,如!、~、+和dot(.)但对于–和++运算符,返回类型必须是“type”类型,对于true和false运算符,返回类型必须是bool类型。但请记住,真运算符和假运算符只能成对重载。如果一个类声明了其中一个运算符而没有声明另一个运算符,则会出现编译错误。
以下语法显示了一元运算符的用法-
operator (object); here, operator is a symbol that denotes a unary operator. operator a;
例子:
Input : 15, -25Output : -15, 25Input : -22, 18Output : 22, -18
C#
// C# program to illustrate the // unary operator overloading using System; namespace Calculator { class Calculator { public int number1 , number2; public Calculator( int num1 , int num2) { number1 = num1; number2 = num2; } // Function to perform operation // By changing sign of integers public static Calculator operator -(Calculator c1) { c1.number1 = -c1.number1; c1.number2 = -c1.number2; return c1; } // Function to print the numbers public void Print() { Console.WriteLine ( "Number1 = " + number1); Console.WriteLine ( "Number2 = " + number2); } } class EntryPoint { // Driver Code static void Main(String []args) { // using overloaded - operator // with the class object Calculator calc = new Calculator(15, -25); calc = -calc; // To display the result calc.Print(); } } } |
输出:
Number1 = -15Number2 = 25
重载二进制运算符
二进制运算符将使用两个操作数。二进制运算符的示例包括 算术运算符 (+,-,*,/,%),算术赋值运算符(+=,-+,*=,/+,%=)和 关系运算符 重载二元运算符与重载一元运算符类似,只是二元运算符需要额外的参数。
语法:
operator operator (object1, object2); Here, second "operator" is a symbol that denotes a binary operator. operator + (a, b);
例子:
Input : 200, 40Output : 240Input : 300, 20 Output : 320
C#
// C# program to illustrate the // Binary Operator Overloading using System; namespace BinaryOverload { class Calculator { public int number = 0; // no-argument constructor public Calculator() {} // parameterized constructor public Calculator( int n) { number = n; } // Overloading of Binary "+" operator public static Calculator operator + (Calculator Calc1, Calculator Calc2) { Calculator Calc3 = new Calculator(0); Calc3.number = Calc2.number + Calc1.number; return Calc3; } // function to display result public void display() { Console.WriteLine( "{0}" , number); } } class CalNum { // Driver Code static void Main( string [] args) { Calculator num1 = new Calculator(200); Calculator num2 = new Calculator(40); Calculator num3 = new Calculator(); num3 = num1 + num2; num1.display(); // Displays 200 num2.display(); // Displays 40 num3.display(); // Displays 240 } } } |
输出:
20040240
操作员超载的好处:
- 运算符重载为 C# 当运算符应用于用户定义的数据类型时。
- 运算符可以被视为编译器内部的函数。