重载操作符
发布日期:2021-05-14 14:40:19 浏览次数:18 分类:精选文章

本文共 2791 字,大约阅读时间需要 9 分钟。

���������������������������

1. ���������

���C#���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

������������������

������������������������������������������

public class MyArray
{
private int[] items;
public MyArray(int capacity)
{
items = new int[capacity];
}
public void SetItem(int i, int val)
{
items[i] = val;
}
public int GetItem(int i)
{
return items[i];
}
// ���������������
public int this[int index]
{
get
{
return items[index];
}
set
{
items[index] = value;
}
}
public int Size()
{
return items.Length;
}
}
������������������

���������������������������������������������������������

MyArray a = new MyArray(4);
a[0] = 12; // ������������������������0���������
a[1] = 12;
a[2] = 12;
a[3] = 12;
for (int i = 0; i < a.Size(); i++)
{
Console.WriteLine(a[i] + " ");
}
a.SetItem(0, 16);
a.SetItem(0, 16);
a.SetItem(0, 16);
a.SetItem(0, 16);
for (int i = 0; i < a.Size(); i++)
{
Console.WriteLine(a.GetItem(i) + " ");
}

������������������������������������������������������������������������������������������������������������������

2. ���������������

���C#������������������������������������������������������������������������������������������������������������MyFraction������������������������������������������������������

MyFraction������������

������������������������������������������������

public class MyFraction
{
public int num = 0;
public int den = 1;
public MyFraction(int num, int den)
{
this.num = num;
this.den = den;
}
public static MyFraction operator *(MyFraction a, MyFraction b)
{
MyFraction res = new MyFraction();
res.num = a.num * b.num;
res.den = a.den * b.den;
return res;
}
}
������������������������

���������������������������������������

  • ���������������������������
  • ������operator������������������������������
  • ������������������������������������������a���b������
  • ���������������������������������������������
  • ������������

    ���������������������������������������������

    using System;
    public class Program
    {
    public static void Main(string[] args)
    {
    MyFraction f1 = new MyFraction(1, 3);
    MyFraction f2 = new MyFraction(2, 5);
    MyFraction res = f1 * f2;
    Console.WriteLine("��������� " + res);
    }
    }

    ������������������������������������������������������������������������������������������������������������

    上一篇:初识文件管理
    下一篇:命名空间

    发表评论

    最新留言

    能坚持,总会有不一样的收获!
    [***.219.124.196]2025年05月02日 10时50分49秒

    关于作者

        喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
    -- 愿君每日到此一游!

    推荐文章