如何实现运算符重载 比如重载:+作者: 许庭洲 时间: 2014-1-6 08:37
1. + 是属于一元运算符重载类型,类似的还有-, !, ~, ++, --, true, false;
2. C# 中的运算符重载是对重载概念的一个重要补充和发展,它针对对象关系中的多元关系和四则运算、关系运算等常规运算提供了重载支持;
3. 例如下面的例子:
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);
}
}////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
First complex number: 2 + 3i
Second complex number: 3 + 4i
The sum of the two numbers: 5 + 7i
// Override the ToString method to display an complex number in the suitable format:
public override string ToString()
{
return (String.Format("{0} + {1}i", real, imaginary));
}
}
C#运算符重载之客户端代码:
static void Main(string[] args)
{
Complex num1 = new Complex(2, 3);
Complex num2 = new Complex(3, 4);
//Add two Complex objects (num1 and num2) through the overloaded plus operator:
Complex sum_Add = num1 + num2;
Complex sum_Minus = num1 - num2;
Complex sum_Product = num1 * num2;
Complex sum_Divide = num1 / num2;
//Print the numbers and the Result using the overriden ToString method:
Console.WriteLine("First complex number: {0}", num1);
Console.WriteLine("Second complex number: {0}", num2);
Console.WriteLine("The sum of the two numbers: {0}", sum_Add);
Console.WriteLine("The Minus of the two numbers: {0}", sum_Minus);
Console.WriteLine("The Product of the two numbers: {0}", sum_Product);
Console.WriteLine("The Divide of the two numbers: {0}", sum_Divide);
Console.ReadLine();
}
C#运算符重载实例运行结果:
First complex number: 2 + 3i
Second complex number: 3 + 4i
The sum of the two numbers: 5 + 7i
The Minus of the two numbers: -1 + -1i
The Product of the two numbers: -6 + 17i
The Divide of the two numbers: 6 + 1i 作者: dongqinglove 时间: 2014-1-6 20:26