Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 运算符重载

作者:霸气邪剑仙   发布日期:2026-04-20   浏览:134

using System;

public class Complex
{
    public int Real { get; set; }
    public int Imaginary { get; set; }

    // 构造函数
    public Complex(int real, int imaginary)
    {
        Real = real;
        Imaginary = imaginary;
    }

    // 重载 + 运算符,用于复数相加
    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }

    // 重载 - 运算符,用于复数相减
    public static Complex operator -(Complex c1, Complex c2)
    {
        return new Complex(c1.Real - c2.Real, c1.Imaginary - c2.Imaginary);
    }

    // 重载 * 运算符,用于复数相乘
    public static Complex operator *(Complex c1, Complex c2)
    {
        return new Complex(
            c1.Real * c2.Real - c1.Imaginary * c2.Imaginary,
            c1.Real * c2.Imaginary + c1.Imaginary * c2.Real
        );
    }

    // 重写 ToString 方法,方便输出
    public override string ToString()
    {
        return $"{Real} + {Imaginary}i";
    }
}

class Program
{
    static void Main()
    {
        Complex num1 = new Complex(3, 4);
        Complex num2 = new Complex(1, 2);

        Complex sum = num1 + num2;
        Console.WriteLine($"Sum: {sum}");

        Complex difference = num1 - num2;
        Console.WriteLine($"Difference: {difference}");

        Complex product = num1 * num2;
        Console.WriteLine($"Product: {product}");
    }
}

解释说明:

  1. 类定义:我们定义了一个 Complex 类来表示复数,包含两个属性 RealImaginary 分别表示复数的实部和虚部。
  2. 构造函数:用于初始化复数对象。
  3. 运算符重载
    • +:重载了加法运算符,实现两个复数的相加。
    • -:重载了减法运算符,实现两个复数的相减。
    • *:重载了乘法运算符,实现两个复数的相乘。
  4. ToString 方法:重写了 ToString 方法,以便于将复数对象转换为字符串格式进行输出。
  5. Main 方法:在 Main 方法中创建了两个复数对象,并演示了如何使用重载的运算符进行加、减、乘操作,并输出结果。

上一篇:c# int转枚举

下一篇:c# 8.0

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站