如果对一个自定义的类型进行加法操作呢?
C#和C++一样,也是用运算符重载来解决此类问题。运算符重载只能用于类或结构中,通过在类(或结构 )中声明并实现一个名为operator x 的方法,即可完成一个运算符的重载。对于一元运算符,其重载 方法需要带一个类或结构类型作为参数;而二元运算符重载 则相应地需要带两个类或结构类型作为参数,二元运算符重载的语法如下:
using System;
namespace OperatorOverLoading
{
//Complex结构体属于一个自定义结构体
public struct Complex
{
int real;
int imaginary;
//带参数的构造函数,real表示实数,imaginary表示虚数
public Complex(int real,int imaginary)
{
//实数部分
this.real = real;
//虚数部分
this.imaginary = imaginary;
}
public static Complex operator +(Complex complex1,Complex complex2)
{
//值类型都有默认无参构造函数
//通过无参构造函数进行初始化
Complex result = new Complex();
//对复数的实数和虚数赋值
result.real = complex1.real + complex2.real;
result.imaginary = complex1.imaginary + complex2.imaginary;
return result;
}
//重载ToString()方法
public override string ToString()
{
return string.Format("{0}+{1}" , real, imaginary);
}
}
class Program
{
static void Main(string[] args)
{
//初始化两个复数
Complex one = new Complex(1,2);
Complex two = new Complex(3,4);
//用+运算符对两个复数进行相加
Complex sum = one+two;
//输出输入的复数和相加之后的结果
Console.WriteLine("{0}", one);
Console.WriteLine("{0}", two);
Console.WriteLine(" =");
Console.WriteLine("{0}", sum);
Console.Read();
}
}
}
执行结果:
C#中允许使用operator关键字来实现运算符的重载,但这并不意味着所有的运算符都可以被重载。如下图所示: