Visual C#2010学习笔记六之运算符的重载

本文详细介绍了如何在C#中通过运算符重载实现复数之间的加法操作,包括定义结构体、重载加号运算符以及自定义toString方法。

运算符的重载是指:允许用户使用自己定义的类型编写表达式,同时还允许用户定义的类型与预定义的类型具有相同的功能。

举个通俗的例子,数学里的加减乘除规则怎么使用大家都知道,在C#中也会默认按照约定俗成的规则来处理,但是如果你想在别的地方也使用加减乘除这几个符号,比如:定义一个字符串+一个字符串得到什么结果,string str1=“xyz”,string str2=“1234”,你肯定希望得到的结果是“xyz1234”;但是当我们也希望用加号,希望得到“xyz”+“1234”=“xyz1234”时,我们就需要重载“+”号,让我重载的“+”号按照我的逻辑执行。重载并不是再出现一次,而是重新生命它的内容,赋予它新的命令。

例子:使用运算符重载定义复数间的加法。

程序如下:

namespace 运算符重载
{
    class Program
    {
        public struct 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)    //重载“+”并返回Complex类型
            {
                return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
            }
            public override string ToString()   //重载ToString
            {
                return (String.Format("{0}+{1}i", real, imaginary));
            }
        }
        static void Main(string[] args)
        {
            Complex num1 = new Complex(1, 2);
            Complex num2 = new Complex(3, 4);
            Complex sum = num1 + num2;
            Console.WriteLine("First complex number:{0}",num1);
            Console.WriteLine("Second complex number:{0}", num2);
            Console.WriteLine("The sum of the two numbers:{0}", sum);
            Console.ReadKey();
        }
    }
}

输出结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值