ostream operator <<
看了前幾篇的文章之後,似乎都是說明居多,本篇的文章整理前幾篇的內容,要開始撰寫實際的應用範例。
寫出自己的輸出格式功能,這一點都不困難。
假設輸出值的欄寬為2個字元,若數字為個位數時,則補零。
舉個例子,若數字為1時,則印出為01;若數字為10時,則直接印10,程式如下:
	//印出020間,偶數數字,並補零對齊
	#include <iostream>
	#include <iomanip>
	using namespace std;
	int main()
	{
		for(int i=0 ; i< 20 ; i += 2 )
			cout<<setw(2)<<setfill('0')<<i<<endl;
		return 0;
	}
輸出:
00
02
04
06
08
10
12
14
16
18
註:
setw(2):設定下一個輸出值的欄寬為2個字元
setfill('0'):設定用以填滿輸出欄位的填補字元'0'
那能不能將上面這兩個只用一個物件或函數代替呢?如下:
	#include <iostream>
	#include <iomanip>
	using namespace std;
	struct n_width_ch_fill
	{	
		int w;
		char ch;
	
		n_width_ch_fill(int width,char symbol):w(width),ch(symbol){}
	};

	inline ostream& operator<<(ostream& os,n_width_ch_fill& nwcf)
	{
		os.width(nwcf.w);
		os.fill(nwcf.ch);
		return os;
	}

	int main()
	{
		for(int i=0 ; i< 20 ; i += 2 )
			cout<<n_width_ch_fill(2,'0')<<i<<endl;
		return 0;
	}
產生一個n_width_ch_fill物件,來記錄所欲輸出的格式,並且直接傳達至輸出。
若輸出功能不須參數的設定,而是以無參數的方式來使用時,是否也能直接接在<<後使用呢?
可以的,像是清除螢幕,可以這樣寫:
	ostream& clrscr(ostream & os)
	{	
		system("CLS"); 
		return os;
	}

	int main()
	{
		cout<<"Hello!"<<endl
		      <<clrscr
		      <<"Clear!"<<endl;
		return 0;
	}

clrscr撰寫方式與操作方式與endlendsflush是一樣的。這個程式有一個問題值得思考,請問清除螢幕與輸出
串流有關係嗎?在clrscr函式中,system("CLS")並沒有與ostream有關,雖然並不會有問題存在。
在撰寫這方面的功能及程式時,最好考慮到是否與output stream(輸出串流)有關,若無關,則以一般的函數撰寫
像:
	int main()
	{
		cout<<"Hello!"<<endl;
		system("CLS");
		cout<<"Clear!"<<endl;
		return 0;
	}
,當然並沒有制式規定一定不能這樣寫,因為有時這樣寫反而更容易使用。
若有關時,再考慮以ostream的方式來撰寫。

 
回目錄
Written By James On 2004/02/08 

Hosted by www.Geocities.ws

1