Program.cs 2.04 KB
Newer Older
Uwe Wienkop's avatar
Uwe Wienkop committed
1
2
3
4
5
6
using System;

namespace _01OperatorOverloading
{
    class Bruch
    {
Uwe Wienkop's avatar
Uwe Wienkop committed
7
        private int z, n;
Uwe Wienkop's avatar
Uwe Wienkop committed
8
        public Bruch(int Z, int N = 1)
Uwe Wienkop's avatar
Uwe Wienkop committed
9
10
11
12
13
14
        {
            z = Z;
            if (N == 0)
                throw new ArgumentNullException("Nenner darf nicht 0 sein!");
            n = N;
        }
Uwe Wienkop's avatar
Uwe Wienkop committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
        public Bruch(string t)
        {
            string[] d = t.Split('/');
            z = Convert.ToInt32(d[0]);
            n = Convert.ToInt32(d[1]);
        }
        public static Bruch Mult1(Bruch b1, Bruch b2)
        {
            int zaehler = b1.z * b2.z;
            int nenner = b1.n * b2.n;

            //b1.z = zaehler;
            //b1.n = nenner;
            Bruch erg = new Bruch(zaehler, nenner);
            return erg;
        }
        public static Bruch Mult2(Bruch b1, Bruch b2)
        {
            return new Bruch(b1.z * b2.z, b1.n * b2.n);
        }
        public static Bruch Mult(Bruch b1, Bruch b2)
            => new Bruch(b1.z * b2.z, b1.n * b2.n);
        public static Bruch operator *(Bruch b1, Bruch b2)
            => new Bruch(b1.z * b2.z, b1.n * b2.n);

        public static explicit operator int(Bruch b)
            => b.z / b.n;
        public static implicit operator double(Bruch b)
            => (double)b.z / (double)b.n;
        public static implicit operator Bruch(int zahl)
            => new Bruch(zahl);


Uwe Wienkop's avatar
Uwe Wienkop committed
48
    }
Uwe Wienkop's avatar
Uwe Wienkop committed
49
50


Uwe Wienkop's avatar
Uwe Wienkop committed
51
52
53
54
    class Program
    {
        static void Main(string[] args)
        {
Uwe Wienkop's avatar
Uwe Wienkop committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
            Bruch b1 = new Bruch(2, 3);
            Bruch b2 = new Bruch(2);
            Bruch b3 = new Bruch("3/4");

            // Bruch e1 = 3.Mult(b1);
            Bruch e2 = Bruch.Mult(b1, b2);
            Bruch e3 = b1 * b2;
            Bruch e4 = b1 * 2;
            Bruch e5 = 2 * b1;
            // 2 --> impl.Konv. in einen Bruch
            // op* (Bruch, Bruch)

            int k = (int)e3;   // explizite Konvertierung
            double d = e3;      // implizite Konvertierung
            Console.WriteLine(k);
            Console.WriteLine(d);

            double d2 = 34;
            int k2 = (int)3.5;
Uwe Wienkop's avatar
Uwe Wienkop committed
74
75
76
        }
    }
}