运算符重载

如果对一个自定义的类型进行加法操作呢?
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关键字来实现运算符的重载,但这并不意味着所有的运算符都可以被重载。如下图所示:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值