105年關務人員四等程式語言概要
一、(一)請說明物件導向式程式語言 (object-oriented programming language) 三大特色。(15分) (二)許多物件導向式程式語言允許程式員定義物件的建構函數 (constructor) 與解構函數 (destructor),請說明建構函數與解構函數的用途。(10分) |
答:
(一)物件導向式程式語言三大特色
1.資料封裝(Encapsulation):
可以將物件區分為可被外界使用的特性及受保護的內部特性。除非是允許外部程式存取的資料,否則外部程式無法改變物件內的資料。如此就能夠達到封裝保護資料的特性。物件導向程式設計將物件的資料與方法至少區分為三種等級(Java 除了下列等級之外,尚有 Package 等級):
(1)public(公用等級):開放給任何程式碼取用。
(2)private(私用等級):只允許相同類別內的程式碼取用。
(3)protected(保護等級):只允許相同類別及衍生類別的程式碼取用。
封裝性使得問題變為分層負責的狀態,更符合生活上的作事原則。
2.繼承(Inheritance):
定義在上層類別 (superclass) 中的資料和程序都能讓下層類別 (subclass) 來繼承,且下層類別亦能修改或增加新的資料和程序。類別的繼承可以大大增加軟體的再用性 (reusability)。若一個類別只能有單一個超類別 (superclass),稱為單一繼承;若一個類別可具有多個直接超類別,稱為多重繼承 (multiple inheritance)。
3.多型(Polymorphism):
一般的多型,是指動態多型,使用繼承和動態繫結來實現。類別與繼承只是達成多型中的一種手段,所以稱物件導向而非類別導向。物件導向程式執行時,相同的訊息可能會送給多個不同型別的物件,而系統可依據物件所屬型別,引發對應型別的方法,而有不同的行為。舉例如下:
#include <iostream.h> class Shape { public: virtual void draw( ) { cout << "Shape\n";} // 虛擬函數 (virtual function) }; class Triangle:virtual public Shape { public: void draw( ) { cout << "Triangle\n";} }; class Circle:virtual public Shape { public: void draw( ) { cout << "Circle\n";} }; void main(void) { Circle ci; Triangle tr; Shape *sp[4] = {&tr, &ci}; // 使用子類別的實做來取代 for(int i = 0; i < 2; i++) sp[i]->draw( ); // 使用動態多型 } |
Shape 陣列物件指到不同的子類別,然後再呼叫 draw method 就可以把各種不同的圖形畫在螢幕上。
※參考資料:
1.http://chihyen-hsiao.blogspot.tw/2013/07/1.html
2.http://notepad.yehyeh.net/Content/CSharp/CH01/03ObjectOrient/3OOCharacter/index.php
3.第七章物件導向設計:類別與物件.pdf
(二)建構函數與解構函數的用途
1.建構函數的用途:
是一種初始化其類別執行個體的成員函式。名稱與類別的名稱相同,但沒有傳回值。可以有任意數目的參數,而類別可以有任意數目的多載建構函式。如果您未定義任何建構函式,則編譯器會產生不接受任何參數的預設建構函式;將預設建構函式宣告為已刪除,即可覆寫這個行為。例如:
#include <iostream> using namespace std; class CPoint { public: int x; int y; // 又稱預設建構函式(default constructor) CPoint(); // 自訂參數的建構函式 CPoint(int x, int y); // 又稱複製建構函式(copy constructor) CPoint(const CPoint &p); }; CPoint::CPoint(): x(0), y(0) { } // 也可以這樣寫 // CPoint::CPoint( ) { x = 0; y = 0; } CPoint::CPoint(int x, int y) { this->x = x; this->y = y; } CPoint::CPoint(const CPoint &p) { x = p.x; y= p.y; } int main(void) { CPoint p; // 呼叫 CPoint::CPoint( ) CPoint *pP = new CPoint(); CPoint q(2, 3); // 呼叫 CPoint::CPoint(int, int) CPoint *pQ = new CPoint(2, 3); CPoint v = q; // 呼叫 CPoint::CPoint(const CPoint &) printf("v = (%d, %d)\n", v.x, v.y); return 0; } |
執行結果:
v = (2, 3)
2.解構函數的用途:
是建構函式的相反。當物件終結時 (取消配置),它們會被呼叫。藉由在類別名稱前面加上波狀符號 (~),將函式指定為類別的解構函式。例如 String 類別的解構函式宣告為 ~String( )。例如:
#include <iostream> using namespace std; class myclass { int a; public: myclass ( ) { a = 10; } ~myclass() { cout << "物件消滅" << endl; } // 解構子 void show() { cout << a << endl; } }; int main(void) { myclass ob; ob.show( ); return 0; } |
執行結果:
10
物件消滅
※參考資料:
1.https://msdn.microsoft.com/zh-tw/library/s16xw1a8.aspx
2.https://msdn.microsoft.com/zh-tw/library/6t4fe76c.aspx
3.http://shukaiyang.myweb.hinet.net/cpp/constructor.zhtw.htm
4.https://www.csie.ntu.edu.tw/~r95116/CA200/slide/C1_C++.pdf