瀏覽單個文章
harrisonlin
Advance Member
 
harrisonlin的大頭照
 

加入日期: Jun 2003
您的住址: Taipei
文章: 442

代碼:
#include <iostream.h>

/*
 *	所有樂器的父類別.
 */
class Instrument {
public:
	/*
	 *	所有的樂器都有"play"的行為,所以不由父類別實作,
	 *  交由衍生類別實作之.
	 */
	virtual void play() = 0;
};


/*
 *	大鼓
 */
class Drum : Instrument {
public:
	void play() {
		cout << "This is Durm playing..." << endl;
	}
};

/*
 *	喇叭
 */
class Horn : Instrument {
public:
	void play() {
		cout << "This is Horn playing..." << endl;
	}
};

/*
 *	吉他
 */
class Guitar : Instrument {
public:
	void play() {
		cout << "This is Guitar playing..." << endl;
	}
};

void main() {
	/*
	 *	產生 3 種樂器.
	 */
	Guitar guitar;
	Drum drum;
	Horn horn;

	/*
	 *	幫我的樂團加入 3 種樂器 - 也就是將各樂器的"指標"記下,之後便透過
	 *  指標操作樂器.注意: myBand 是一個儲存 Instrument* 的指標陣列.
	 */
	Instrument* myBand[] = {(Instrument*)&guitar,
							(Instrument*)&drum,
							(Instrument*)&horn};

	/*
	 *	將 myBand 的樂器一一操作.在這裡我不需要知道是什麼樂器,只要呼叫它的 "play()"
	 *  就可以了!這就是"多型(Polymorphism)"的好處!!而"多型"在C++中就是透過 virtual function 來達成!
	 */
	for(int index = 0; index < 3; ++index) {
		myBand[index]->play();
	}
}
__________________
現今世道,自爆文當故事書,站長的話做成語錄,幾百年前的文章嘛沒事就挖出來考古...
舊 2004-06-01, 02:10 PM #5
回應時引用此文章
harrisonlin離線中