点点滴滴访问量:
 C#中预定义的运算符的操作对象只能是基本数据类型。实际上,对于许多用户自定义类型(例如类),也需要类似的运算操作。这时就必须在C#中重新定义这些运算符,赋予已有运算符新的功能,使它能够用于特定类型执行特定的操作。

   运算符重载实质上是函数重载。在表达式中,使用运算符表示法(即符号)来引用运算符,而在声明中,使用函数表示法来引用运算符。

运算符重载是通过创建运算符函数来实现的,运算符函数定义了重载的运算符将要进行的操作,运算符函数的定义与其他函数 的定义类似,惟一的区别是运算符函数的函数名是由关键字operator和其后要重载的运算符符号构成的。

 

例:

using System;

 

namespace yunsuanfuchongzai

{

    public class Complex //定义一个复数类

    {

        public int real;

        public int imaginary;

 

        public Complex(int real,int imaginary)

        {

            this.real = real;

            this.imaginary = imaginary;

        }

 

        public static Complex operator +(Complex c1,Complex c2)//声明对‘+’运算符的重载

        {

            return new Complex(c1.real + c2.real,c1.imaginary + c2.imaginary);

        }

 

        public override string ToString()   //重写ToString方法,以特定的格式显示复数

        {

            return(String.Format("{0} + {1}i",real,imaginary));

        }

 

        [STAThread]

        static void Main(string[] args)

        {

            Complex num1 = new Complex(2,3);

            Complex num2 = new Complex(3,4);

 

            Complex sum = num1 + num2;//使用重载后的‘+’运算符对两个复数进行运算

 

            Console.WriteLine("First complex number: {0}",num1.ToString());//使用重载后的ToString方法显示

            Console.WriteLine("second complex number: {0}",num2.ToString());//两个复数以及它们相加后的结果

            Console.WriteLine("the sum of the two number: {0}",sum.ToString());

        }

    }

 

}

posted on 2006-04-13 16:37  sopper  阅读(668)  评论(0编辑  收藏  举报