プログラミング(Python、Perl、C、Go、JavaScript)、数学、読書…
開発環境
"初めてのC# 第2版"のp.211, 第12章(演算子のオーバーロード)の12.6(練習問題)、練習 12-1, 2を解いてみる。
練習 12-1
練習 12-2
using System; public class Invoice { private string vendor; private double amount; public Invoice(string vendor, double amount) { this.vendor = vendor; this.amount = amount; } public static Invoice operator+( Invoice lhs, Invoice rhs) { if(lhs.vendor==rhs.vendor) { return new Invoice( lhs.vendor,lhs.amount+rhs.amount); } return new Invoice("",0); } public static bool operator ==(Invoice lhs, Invoice rhs) { if (lhs.vendor == rhs.vendor && lhs.amount == rhs.amount) { return true; } return false; } public static bool operator !=(Invoice lhs, Invoice rhs) { return !(lhs == rhs); } public override bool Equals(object obj) { if (!(obj is Invoice)) { return false; } return this == (Invoice)obj; } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { String s = vendor.ToString() + ":" + amount.ToString(); return s; } } class Tester { public void Run() { Invoice i1 = new Invoice("Vendor", 1.2); Invoice i2 = new Invoice("Vendor", 1.2); Invoice i3 = new Invoice("Vendor", 1.3); Invoice i4 = new Invoice("Vendor1", 1.2); Console.WriteLine("i1={0}, i2={1}, i3={2}, i4={3}", i1.ToString(), i2.ToString(), i3.ToString(), i4.ToString()); if (i1 == i2) { Console.WriteLine("i1=i2"); } if (i1 != i3) { Console.WriteLine("i1!=i3"); } if (i1 != i4) { Console.WriteLine("i1!=i4"); } if (i1.Equals(i2)) { Console.WriteLine("i1.Equals(i2)"); } } static void Main() { Tester t = new Tester(); t.Run(); } }
0 コメント:
コメントを投稿