開発環境
- Microsoft Windows 7 Home Premium (OS)
- Microsoft Visual C# 2010 Express Edition (IDE)
- 言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第12章(演算子のオーバーロード)12.6(練習問題)、練習12-1を解いてみる。
練習12-1.
コード
using System;
namespace Sample
{
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 string Vendor
{
get { return vendor; }
}
public double Amount
{
get { return amount; }
}
}
class Tester
{
public void Run()
{
Invoice a = new Invoice("invoice1", 10);
Invoice b = new Invoice("invoice1", 20);
Invoice c = new Invoice("invoice2", 10);
Invoice d = new Invoice("invoice2", 20);
Invoice[] invoices = { b, c, d };
foreach (Invoice invoice in invoices)
{
Console.WriteLine("({0},{1}) + ({2},{3}) = ({4},{5})",
a.Vendor, a.Amount, invoice.Vendor, invoice.Amount,
(a + invoice).Vendor, (a + invoice).Amount);
}
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
}
入出力結果(Console Window)
(invoice1,10) + (invoice1,20) = (invoice1,30) (invoice1,10) + (invoice2,10) = (,0) (invoice1,10) + (invoice2,20) = (,0) 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿