C# 运算符重载

重载运算符
public struct Complex
{
public int real;
public int imaginary;

public Complex(int real, int imaginary) //constructor
{
this.real = real;
this.imaginary = imaginary;
}

// Declare which operator to overload (+),
// the types that can be added (two Complex objects),
// and the return type (Complex):
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}

// Override the ToString() method to display a complex number in the traditional format:
public override string ToString()
{
return (System.String.Format("{0} + {1}i", real, imaginary));
}
}

class TestComplex
{
static void Main()
{
Complex num1
= new Complex(2, 3);
Complex num2
= new Complex(3, 4);

// Add two Complex objects through the overloaded plus operator:
Complex sum = num1 + num2;

// Print the numbers and the sum using the overriden ToString method:
System.Console.WriteLine("First complex number: {0}", num1);
System.Console.WriteLine(
"Second complex number: {0}", num2);
System.Console.WriteLine(
"The sum of the two numbers: {0}", sum);
}
}


可重载的运算符:

C# 允许用户定义的类型通过使用 operator 关键字定义静态成员函数来重载运算符。但不是所有的运算符都可被重载,下表列出了不能被重载的运算符:
运算符     可重载性

——————————————————————————————

+、-、!、~、++、--、true 和 false

可以重载这些一元运算符。
——————————————————————————————
+, -, *, /, %, &, |, ^, <<, >>
可以重载这些二进制运算符。

——————————————————————————————
==, !=, <, >, <=, >=
比较运算符可以重载(但请参见本表后面的说明)。

——————————————————————————————
&&, || 
条件逻辑运算符不能重载,但可使用能够重载的 & 和 | 进行计算。

——————————————————————————————
[]
不能重载数组索引运算符,但可定义索引器。

——————————————————————————————
() 
不能重载转换运算符,但可定义新的转换运算符(请参见 explicit 和 implicit)。

——————————————————————————————
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
赋值运算符不能重载,但 += 可使用 + 计算,等等。
——————————————————————————————
=、.、?:、->、new、is、sizeof 和 typeof  
不能重载这些运算符。
——————————————————————————————

注意
比较运算符(如果重载)必须成对重载;也就是说,如果重载 ==,也必须重载 !=。反之亦然,< 和 > 以及 <= 和 >= 同样如此。
若要在自定义类中重载运算符,您需要在该类中创建具有正确签名的方法。该方法必须命名为“operator X”,其中 X 是正在重载的运算符的名称或符号。一元运算符具有一个参数,二元运算符具有两个参数。在每种情况下,参数的类型必须与声明该运算符的类或结构的类型相同,如下面的示例所示:

public static Complex operator +(Complex c1, Complex c2)




返回导读目录,阅读更多随笔



分割线,以下为博客签名:

软件臭虫情未了
  • 编码一分钟
  • 测试十年功


随笔如有错误或不恰当之处、为希望不误导他人,望大侠们给予批评指正。

原文地址:https://www.cnblogs.com/08shiyan/p/1887281.html