類別與物件 ii (classes and objects ii)

47
1 類類類類類 類類類類類 II II (Classes and Objects (Classes and Objects II) II) 鄭鄭鄭 鄭鄭鄭 鄭鄭鄭鄭鄭鄭 鄭鄭鄭鄭鄭鄭 鄭鄭鄭鄭鄭鄭 鄭鄭鄭鄭鄭鄭 / / 鄭鄭鄭鄭鄭鄭鄭 鄭鄭鄭鄭鄭鄭鄭 / / 鄭鄭鄭鄭鄭鄭鄭 鄭鄭鄭 鄭鄭鄭鄭鄭鄭鄭 鄭鄭鄭

Upload: ownah

Post on 20-Mar-2016

57 views

Category:

Documents


1 download

DESCRIPTION

類別與物件 II (Classes and Objects II). 鄭士康 國立台灣大學 電機工程學系 / 電信工程研究所 / 資訊網路與多媒體研究所. 程式 DiceSimulation.Program (1/3). using System; namespace DiceSimulation { /* * 模擬擲骰子示範類別的宣告與物件的使用 * 使用類別 Dice 的建構 函式 * 3/23/2008 */ class Program { - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: 類別與物件  II (Classes and Objects II)

1

類別與物件 類別與物件 IIII(Classes and Objects II)(Classes and Objects II)鄭士康鄭士康國立台灣大學國立台灣大學電機工程學系電機工程學系 // 電信工程研究所電信工程研究所 //資訊網路與多媒體研究所資訊網路與多媒體研究所

Page 2: 類別與物件  II (Classes and Objects II)

2

程式 程式 DiceSimulation.Program DiceSimulation.Program (1/3)(1/3)using System;using System;namespace DiceSimulationnamespace DiceSimulation{{ /*/* * * 模擬擲骰子示範類別的宣告與物件的使用模擬擲骰子示範類別的宣告與物件的使用 * * 使用類別使用類別 DiceDice的建構的建構函式函式 * 3/23/2008* 3/23/2008 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{

Page 3: 類別與物件  II (Classes and Objects II)

3

程式 程式 DiceSimulation.Program DiceSimulation.Program (2/3)(2/3)int[] count = new int[6]; // int[] count = new int[6]; // 累計點數出現次數累計點數出現次數

for (int i = 0; i < 6; ++i)for (int i = 0; i < 6; ++i) {{ count[i] = 0;count[i] = 0; }} const int N = 12000; // const int N = 12000; // 總擲骰次數總擲骰次數 int seed = 123;int seed = 123; Dice dice = new Dice( seed );Dice dice = new Dice( seed ); int faceValue;int faceValue; // // 擲骰擲骰 NN次次 for (int i = 0; i < N; ++i)for (int i = 0; i < N; ++i) {{ faceValue = dice.FaceValue;faceValue = dice.FaceValue; ++count[faceValue-1];++count[faceValue-1]; dice.Toss();dice.Toss(); }}

Page 4: 類別與物件  II (Classes and Objects II)

4

程式 程式 DiceSimulation.Program DiceSimulation.Program (3/3)(3/3) // // 印出結果印出結果

for (int i = 0; i < 6; ++i)for (int i = 0; i < 6; ++i) {{ Console.WriteLine(" {0} appears {1} times ", Console.WriteLine(" {0} appears {1} times ",

i + 1, count[i]);i + 1, count[i]); }} }} }}}}

Page 5: 類別與物件  II (Classes and Objects II)

5

程式 程式 DiceSimulation.Dice (1DiceSimulation.Dice (1/2)/2)using System;using System;namespace DiceSimulationnamespace DiceSimulation{{ /*/* * * 骰子骰子 * 3/23/2008* 3/23/2008 */*/ public class Dicepublic class Dice {{ int faceValue;int faceValue; Random rand;Random rand; public Dice()public Dice() {{ rand = new Random();rand = new Random(); Toss();Toss(); }}

Page 6: 類別與物件  II (Classes and Objects II)

6

程式 程式 DiceSimulation.Dice (2DiceSimulation.Dice (2/2)/2) public Dice(int seed)public Dice(int seed)

{{ rand = new Random(seed);rand = new Random(seed); Toss();Toss(); }} public int FaceValuepublic int FaceValue {{ get { return faceValue; }get { return faceValue; } set { faceValue = value; }set { faceValue = value; } }} public void Toss()public void Toss() {{ faceValue = rand.Next() % 6 + 1;faceValue = rand.Next() % 6 + 1; }} }}}}

Page 7: 類別與物件  II (Classes and Objects II)

7

建構函式與解構函式建構函式與解構函式(Constructor and Destructor)(Constructor and Destructor)• 預設建構函式預設建構函式 (default constructor)(default constructor)• 具參數之建構函式具參數之建構函式

– 檢驗參數範圍檢驗參數範圍• 解構函式解構函式

Page 8: 類別與物件  II (Classes and Objects II)

8

物件產生與消滅流程物件產生與消滅流程static void main( string[] arg ){

Dice dice = new Dice( seed );

public Dice(int seed){ . . . }

}~Dice() { . . . }

刪除物件 dice

離開主函數 , 程式結束

物件宣告 物件生成

Page 9: 類別與物件  II (Classes and Objects II)

9

存取修飾詞存取修飾詞 (Access Modifier(Access Modifiers)s)• publicpublic• privateprivate• protectedprotected• internalinternal

Page 10: 類別與物件  II (Classes and Objects II)

10

練習練習• 修改類別修改類別 CardCard ,改用建構函式設定初值,,改用建構函式設定初值,以屬性取得以屬性取得 suitsuit 及及 faceValuefaceValue

Card

suit : char

SuitFaceValue

faceValue : int

Page 11: 類別與物件  II (Classes and Objects II)

11

程式 程式 UsingStatic.Program (1UsingStatic.Program (1/2)/2)using System;using System;namespace UsingStaticnamespace UsingStatic{{ /* /* 示範靜態成員之使用示範靜態成員之使用 * 3/27/2007* 3/27/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ Console.WriteLine(Console.WriteLine( ""請輸入要轉換的小時數與天數請輸入要轉換的小時數與天數 , , 以一個空格分開以一個空格分開 ");"); string[] input = string[] input = (Console.ReadLine()).Split(' ');(Console.ReadLine()).Split(' '); int hours = int.Parse(input[0]);int hours = int.Parse(input[0]); int days = int.Parse(input[1]);int days = int.Parse(input[1]);

Page 12: 類別與物件  II (Classes and Objects II)

12

程式 程式 UsingStatic.Program (2UsingStatic.Program (2/2)/2) int hoursToMins = int hoursToMins = TimeConversion.HoursToMins(hours);TimeConversion.HoursToMins(hours); int daysToHours = int daysToHours = TimeConversion.DaysToHours(days);TimeConversion.DaysToHours(days); Console.WriteLine(hours + " hours = " + Console.WriteLine(hours + " hours = " + hoursToMins + " minutes");hoursToMins + " minutes"); Console.WriteLine(days + " days = " + Console.WriteLine(days + " days = " + daysToHours + " hours");daysToHours + " hours"); Test t1 = new Test();Test t1 = new Test(); Test t2 = new Test();Test t2 = new Test(); Console.WriteLine(Test.GetNConstructed + Console.WriteLine(Test.GetNConstructed + " Test objects were constructed"); " Test objects were constructed"); Console.ReadLine();Console.ReadLine(); }} }}}}

Page 13: 類別與物件  II (Classes and Objects II)

13

程式 程式 UsingStatic.TimeConversion UsingStatic.TimeConversion (1/2)(1/2)using System;using System;namespace UsingStaticnamespace UsingStatic{{ /*/* * collection of time conversion routines* collection of time conversion routines * 3/27/2007* 3/27/2007 */*/ public public static static class TimeConversionclass TimeConversion {{ private const int HOURS_PER_DAY = 24;private const int HOURS_PER_DAY = 24; private const int MINS_PER_HOUR = 60;private const int MINS_PER_HOUR = 60;

Page 14: 類別與物件  II (Classes and Objects II)

14

程式 程式 UsingStatic.TimeConversion UsingStatic.TimeConversion (2/2)(2/2) public static int HoursToMins( int hours )public static int HoursToMins( int hours ) {{

return hours*MINS_PER_HOUR;return hours*MINS_PER_HOUR; }} public static int DaysToHours( int days )public static int DaysToHours( int days ) {{

return days*HOURS_PER_DAY;return days*HOURS_PER_DAY; }}

}}}}

Page 15: 類別與物件  II (Classes and Objects II)

15

程式 程式 UsingStatic.TestUsingStatic.Testusing System;using System;namespace UsingStaticnamespace UsingStatic{{ public class Testpublic class Test {{ private static int nConstructed = 0;private static int nConstructed = 0; public Test()public Test() {{ ++nConstructed;++nConstructed; }} public static int GetNConstructedpublic static int GetNConstructed {{ getget {{ return nConstructed;return nConstructed; }} }} }}}}

Page 16: 類別與物件  II (Classes and Objects II)

16

靜態成員與靜態類別靜態成員與靜態類別• 常數宣告常數宣告• 靜態成員應用場合靜態成員應用場合• 靜態函式靜態函式 MainMain• 靜態類別應用場合靜態類別應用場合

Page 17: 類別與物件  II (Classes and Objects II)

17

靜態成員的記憶配置靜態成員的記憶配置t1

記憶體地址 1

t2

記憶體地址 2

函式成員 Test 進入點

函式 Test() 進入地址

函式 Test() 進入地址

nConstructedTest

函式成員GetNConstructed 進入點

記憶體地址

Page 18: 類別與物件  II (Classes and Objects II)

18

練習 練習 (1/2)(1/2)• 在類別在類別 CardCard 內增加靜態成員函式,累計產內增加靜態成員函式,累計產生的生的 CardCard 物件數物件數• 寫一程式利用類別寫一程式利用類別 CardCard 產生全副撲克牌,產生全副撲克牌,放在陣列放在陣列 deckdeck 內內

Page 19: 類別與物件  II (Classes and Objects II)

19

練習 練習 (2/2)(2/2)• 實作並測試一靜態類別實作並測試一靜態類別 EqSolverEqSolver ,內含,內含兩靜態成員函式兩靜態成員函式 double Linear(doubldouble Linear(double a, double b)e a, double b) 及及 double Quadratidouble Quadratic(double a, double b, double c)c(double a, double b, double c)分別解一次方程式分別解一次方程式 a a xx + b = 0 + b = 0 及及 a a xx22 + b + b xx + + c = 0c = 0

Page 20: 類別與物件  II (Classes and Objects II)

20

運算子多載運算子多載• 可以多載可以多載

– 一元一元:: ++ 、、 -- 、、 !! 、、 ~~ 、、 ++++ 、、 ---- 、、 truetrue 、、 falsefalse – 二元:二元: ++ 、、 -- 、、 ** 、、 // 、、 %% 、、 && 、、 || 、、 ^̂ 、、 <<<< 、、 >>>> 、、==== 、、 !=!= 、、 >> 、、 << 、、 >=>= 、、 <=<=

• 不可多載不可多載– == 、、 .. 、、 &&&& 、、 |||| 、、 ?:?: 、、 [] [] 、、 () () 、、 ->-> 、、 newnew 、、 isis 、、sizeofsizeof 、、 typeoftypeof 、、 +=+= 、、 -=-= 、、 *=*= 、、 /=/= 、、 %=%= 、、 &&== 、、 |=|= 、、 ^=^= 、、 <<=<<= 、、 >>=>>=

• 轉換運算子轉換運算子– explicit explicit 關鍵字關鍵字– Implicit Implicit 關鍵字關鍵字

Page 21: 類別與物件  II (Classes and Objects II)

21

UsingOperOverload.ProgUsingOperOverload.Program(1/2)ram(1/2)

using System;using System;namespace UsingOperOverloadnamespace UsingOperOverload{{ /* /* 示範一元運算子多載示範一元運算子多載 * 4/9/2007* 4/9/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ Rectangle rec = new Rectangle(100, 50);Rectangle rec = new Rectangle(100, 50); Console.WriteLine("Console.WriteLine("長方形長方形 recrec的面積的面積 : " + : " + rec.Area());rec.Area());

Page 22: 類別與物件  II (Classes and Objects II)

22

UsingOperOverload.ProgUsingOperOverload.Program(2/2)ram(2/2)

rec++;rec++; Console.WriteLine("Console.WriteLine("長方形長方形 rec++rec++後的面積後的面積 : " + : " +

rec.Area());rec.Area()); // // 應為 應為 51515151 ++rec;++rec; Console.WriteLine("Console.WriteLine("長方形長方形 ++rec++rec後的面積後的面積 : " + : " +

rec.Area());rec.Area()); // // 應為 應為 53045304 Console.ReadLine();Console.ReadLine(); }} }}}}

Page 23: 類別與物件  II (Classes and Objects II)

23

UsingOperOverload.RectanUsingOperOverload.Rectangle(1/2)gle(1/2)

using System;using System;namespace UsingOperOverloadnamespace UsingOperOverload{{ public class Rectanglepublic class Rectangle {{ private int width;private int width; private int length;private int length; private int area;private int area; public Rectangle(int width, int length)public Rectangle(int width, int length) {{ this.width = width;this.width = width; this.length = length;this.length = length; area = width * length;area = width * length; }}

Page 24: 類別與物件  II (Classes and Objects II)

24

UsingOperOverload.RectanUsingOperOverload.Rectangle(2/2)gle(2/2)

public int Area()public int Area() {{ return area; return area; }} public static Rectangle operator ++(Rectangle public static Rectangle operator ++(Rectangle

op)op) {{ Rectangle result = new Rectangle(op.width+1, Rectangle result = new Rectangle(op.width+1,

op.length+1);op.length+1); return result;return result; }} }}}}

Page 25: 類別與物件  II (Classes and Objects II)

25

UsingOperOverload2.PrograUsingOperOverload2.Program(1/2)m(1/2)

using System;using System;namespace UsingOperOverload2namespace UsingOperOverload2{{ /*/* * * 示範二元運算子示範二元運算子多載的應用多載的應用 * 4/9/2007* 4/9/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ Rectangle rec1 = new Rectangle(100, 50);Rectangle rec1 = new Rectangle(100, 50); Rectangle rec2 = new Rectangle(90, 25);Rectangle rec2 = new Rectangle(90, 25); Rectangle recSum = rec1 + rec2;Rectangle recSum = rec1 + rec2; Rectangle recDif = rec1 - rec2;Rectangle recDif = rec1 - rec2;

Page 26: 類別與物件  II (Classes and Objects II)

26

UsingOperOverload2.PrograUsingOperOverload2.Program(2/2)m(2/2)

// recSum.Area() // recSum.Area() 應為應為 1425014250 Console.WriteLine("rec1 + rec2 Console.WriteLine("rec1 + rec2 的面積的面積 : " + : " +

recSum.Area());recSum.Area());

// recDif.Area() // recDif.Area() 應為應為 250250 Console.WriteLine("rec1 - rec2 Console.WriteLine("rec1 - rec2 的面積的面積 : " + : " +

recDif.Area());recDif.Area()); Console.ReadLine();Console.ReadLine(); }} }}}}

Page 27: 類別與物件  II (Classes and Objects II)

27

UsingOperOverload2.RectaUsingOperOverload2.Rectangle(1/2)ngle(1/2)

using System;using System;

namespace UsingOperOverload2namespace UsingOperOverload2{{ class Rectangleclass Rectangle {{ private int width;private int width; private int length;private int length; private int area;private int area; public Rectangle(int width, int length)public Rectangle(int width, int length) {{ this.width = width;this.width = width; this.length = length;this.length = length; area = width * length;area = width * length; }}

Page 28: 類別與物件  II (Classes and Objects II)

28

UsingOperOverload2.RectaUsingOperOverload2.Rectangle(2/2)ngle(2/2)

public int Area()public int Area() {{ return area;return area; }} public static Rectangle operator +(Rectangle op1, public static Rectangle operator +(Rectangle op1,

Rectangle op2)Rectangle op2) {{ Rectangle result = new Rectangle(Rectangle result = new Rectangle( op1.width + op2.width, op1.length + op2.length);op1.width + op2.width, op1.length + op2.length); return result;return result; }} public static Rectangle operator -(Rectangle op1, public static Rectangle operator -(Rectangle op1,

Rectangle op2){Rectangle op2){ Rectangle result = new Rectangle(Rectangle result = new Rectangle(

op1.width - op2.width, op1.length - op2.length);op1.width - op2.width, op1.length - op2.length); return result;return result; }} }}}}

Page 29: 類別與物件  II (Classes and Objects II)

29

運算子執行流程運算子執行流程Rectangle recSum = rec1 + rec2;

public static Rectangle operatorpublic static Rectangle operator +(Rectangle op1, +(Rectangle op1, Rectangle op2)Rectangle op2) {{

return result;

}

Rectangle result = new Rectangle(Rectangle result = new Rectangle( op1.width + op2.width, op1.width + op2.width, op1.length + op2.length);op1.length + op2.length);

Page 30: 類別與物件  II (Classes and Objects II)

30

練習練習• 撰寫測試主程式及類別撰寫測試主程式及類別 RationalRational(( 有理有理數數 )) ,其中須測試及定義,其中須測試及定義有理數有理數 ++ 、、 -- 、、 ** 、、// 、、 ++++ 運算子。可不必考慮約分。運算子。可不必考慮約分。

Page 31: 類別與物件  II (Classes and Objects II)

31

RelOperOverload.PrograRelOperOverload.Program(1/2)m(1/2)

using System;using System;namespace RelOperOverloadnamespace RelOperOverload{{ /*/* * * 示範關聯運算子示範關聯運算子 >>和和 <<的多載的多載 * 4/11/2007* 4/11/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ StudentClass clsA = new StudentClass(20);StudentClass clsA = new StudentClass(20); StudentClass clsB = new StudentClass(30);StudentClass clsB = new StudentClass(30); bool clsAIsLarger = clsA > clsB;bool clsAIsLarger = clsA > clsB; string message = clsAIsLarger ? string message = clsAIsLarger ?

"A"A班人數大於班人數大於 BB班班 " : "A" : "A班人數不大於班人數不大於 BB班班 ";";

Page 32: 類別與物件  II (Classes and Objects II)

32

RelOperOverload.PrograRelOperOverload.Program(2/2)m(2/2)

Console.WriteLine(message);Console.WriteLine(message); Console.ReadLine();Console.ReadLine(); }} }}}}

Page 33: 類別與物件  II (Classes and Objects II)

33

RelOperOverload.StudentClRelOperOverload.StudentClass(1/3)ass(1/3)using System;using System;

namespace RelOperOverloadnamespace RelOperOverload{{ public class StudentClasspublic class StudentClass {{ private int nStudents;private int nStudents; public StudentClass(int nStudents)public StudentClass(int nStudents) {{ if (nStudents < 0)if (nStudents < 0) {{ this.nStudents = 0;this.nStudents = 0; }} elseelse {{ this.nStudents = nStudents;this.nStudents = nStudents; }} }}

Page 34: 類別與物件  II (Classes and Objects II)

34

RelOperOverload.StudentClRelOperOverload.StudentClass(2/3)ass(2/3)

public int accessNStudentspublic int accessNStudents {{ getget {{ return nStudents;return nStudents; }} }} public static bool operator >(StudentClass op1, public static bool operator >(StudentClass op1, StudentClass op2)StudentClass op2) {{ bool result = (op1.nStudents > op2.nStudents);bool result = (op1.nStudents > op2.nStudents); return result;return result; }}

Page 35: 類別與物件  II (Classes and Objects II)

35

RelOperOverload.StudentClRelOperOverload.StudentClass(3/3)ass(3/3)

public static bool operator <(StudentClass op1, public static bool operator <(StudentClass op1, StudentClass op2)StudentClass op2) {{ bool result = (op1.nStudents < op2.nStudents);bool result = (op1.nStudents < op2.nStudents); return result;return result; }} }}}}

Page 36: 類別與物件  II (Classes and Objects II)

36

練習練習• 在類別在類別 RationalRational(( 有理數有理數 )) 中添加中添加有理數有理數>> 、、 << 、、 !!(( 檢驗是否為檢驗是否為 0)0) 運算子,並予測運算子,並予測試。試。

• 處理處理 RationalRational(( 有理數有理數 )) 類別與整數進行類別與整數進行++ 、、 -- 、、 ** 、、 // 的情形的情形

Page 37: 類別與物件  II (Classes and Objects II)

37

RelOperOverload2.ProgrRelOperOverload2.Program(1/2)am(1/2)

using System;using System;namespace RelOperOverload2namespace RelOperOverload2{{ /*/* * * 示範關聯運算子示範關聯運算子 ==,!=,Equals,GetHashCode==,!=,Equals,GetHashCode等的多載等的多載 * 4/11/2007* 4/11/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ StudentClass clsA = new StudentClass("A", 20);StudentClass clsA = new StudentClass("A", 20); StudentClass clsB = new StudentClass("B", 20);StudentClass clsB = new StudentClass("B", 20); bool clsAEqualsclsB = clsA == clsB;bool clsAEqualsclsB = clsA == clsB; string message = clsAEqualsclsB ? string message = clsAEqualsclsB ? ““clsAclsA與與 clsBclsB 相相等等”” : “: “clsAclsA 與與 clsBclsB 不等不等 ";";

Page 38: 類別與物件  II (Classes and Objects II)

38

RelOperOverload2.ProgrRelOperOverload2.Program(2/2)am(2/2)

Console.WriteLine(message);Console.WriteLine(message); clsAEqualsclsB = clsA.Equals(clsB);clsAEqualsclsB = clsA.Equals(clsB); message = clsAEqualsclsB ? “clsAmessage = clsAEqualsclsB ? “clsA與與 clsBclsB 相相等等 ": ":

““clsAclsA 與與 clsBclsB 不等不等 "; "; Console.WriteLine(message);Console.WriteLine(message); Console.ReadLine();Console.ReadLine(); }} }}}}

Page 39: 類別與物件  II (Classes and Objects II)

39

RelOperOverload2.StudentRelOperOverload2.StudentClass(1/3)Class(1/3)

using System;using System;namespace RelOperOverload2namespace RelOperOverload2{{ public class StudentClasspublic class StudentClass {{ private int nStudents;private int nStudents; private string name;private string name; public StudentClass(string name, int nStudents)public StudentClass(string name, int nStudents) {{ this.name = name;this.name = name; if (nStudents < 0)if (nStudents < 0) {{ this.nStudents = 0;this.nStudents = 0; }}

Page 40: 類別與物件  II (Classes and Objects II)

40

RelOperOverload2.StudentRelOperOverload2.StudentClass(2/3)Class(2/3)

elseelse {{ this.nStudents = nStudents;this.nStudents = nStudents; }} }} public static bool operator ==(StudentClass op1, public static bool operator ==(StudentClass op1,

StudentClass op2)StudentClass op2) {{ bool result = ( op1.name.Equals(op2.name) ) && bool result = ( op1.name.Equals(op2.name) ) &&

(op1.nStudents == op2.nStudents);(op1.nStudents == op2.nStudents); return result;return result; }} public static bool operator !=(StudentClass op1, public static bool operator !=(StudentClass op1,

StudentClass op2)StudentClass op2) {{ return !(op1 == op2);return !(op1 == op2); }}

Page 41: 類別與物件  II (Classes and Objects II)

41

RelOperOverload2.StudentRelOperOverload2.StudentClass(3/3)Class(3/3)

public override bool Equals(object obj)public override bool Equals(object obj) {{ bool result = false;bool result = false; if (obj is StudentClass)if (obj is StudentClass) {{ StudentClass op = (StudentClass) obj;StudentClass op = (StudentClass) obj; result = name.Equals(op.name) && result = name.Equals(op.name) && (nStudents == op.nStudents);(nStudents == op.nStudents); }} return result; return result; }} public override int GetHashCode()public override int GetHashCode() {{ return nStudents.GetHashCode() + return nStudents.GetHashCode() + name.GetHashCode();name.GetHashCode(); }} }}}}

Page 42: 類別與物件  II (Classes and Objects II)

42

ConvertOper.Program (1/2) ConvertOper.Program (1/2) using System;using System;namespace Convernamespace ConverttOperOper{{ /*/* * * 示範示範 explicitexplicit與與 implicitimplicit的轉換的轉換 * 4/11/2007* 4/11/2007 */*/ class Programclass Program {{ static void Main(string[] args)static void Main(string[] args) {{ Rectangle rec = new Rectangle(15, 10);Rectangle rec = new Rectangle(15, 10); int area = (int) rec; int area = (int) rec;

Console.WriteLine("recConsole.WriteLine("rec面積為面積為 " + area);" + area); Square sq = new Square(20);Square sq = new Square(20);

Page 43: 類別與物件  II (Classes and Objects II)

43

ConvertOper.Program (2/2)ConvertOper.Program (2/2) rec = sq;rec = sq;

area = (int)rec; area = (int)rec; Console.WriteLine("sqConsole.WriteLine("sq面積為面積為 " + area);" + area);

Console.ReadLine();Console.ReadLine(); }} }}}}

Page 44: 類別與物件  II (Classes and Objects II)

44

ConvertOper.Rectangle (1/2)ConvertOper.Rectangle (1/2)using System;using System;namespace ConverOpernamespace ConverOper{{ public class Rectanglepublic class Rectangle {{ int width;int width; int length;int length; int area;int area; public Rectangle(int width, int length)public Rectangle(int width, int length) {{ this.width = width;this.width = width; this.length = length;this.length = length; area = length * width;area = length * width; }}

Page 45: 類別與物件  II (Classes and Objects II)

45

ConvertOper.Rectangle (2/2)ConvertOper.Rectangle (2/2) public static public static explicitexplicit operator int(Rectangle operator int(Rectangle op)op)

{{ return op.area;return op.area; }} }}}}

Page 46: 類別與物件  II (Classes and Objects II)

46

ConvertOper.SquareConvertOper.Squareusing System;using System;namespace Convernamespace ConverttOperOper{{ public class Squarepublic class Square {{ private int width;private int width; public Square(int width)public Square(int width) {{ this.width = width;this.width = width; }} public static public static implicitimplicit operator operator Rectangle( Square op ) {Rectangle( Square op ) { Rectangle rec = new Rectangle( op.width, Rectangle rec = new Rectangle( op.width, op.width );op.width ); return rec;return rec; }} }}}}

Page 47: 類別與物件  II (Classes and Objects II)

47

練習練習• 在類別在類別 RationalRational(( 有理數有理數 )) 中添加中添加有理數有理數==== 、、 !=!= 運算子及運算子及 EqualsEquals 、、 GetHashCoGetHashCodede 方法方法,並予測試。,並予測試。

• 在類別在類別 RationalRational(( 有理數有理數 )) 中添加轉為中添加轉為 dodoubleuble 的的 explicitexplicit 運算子,及運算子,及 intint 轉為轉為 RatRationalional 的的 implicitimplicit 運算子運算子