ostream operator <<
先來看看ostream << 有的項目,查至標題檔ostream.h
inline  ostream& operator<<(ostream& (__cdecl * _f)(ostream&));
inline  ostream& operator<<(ios& (__cdecl * _f)(ios&));
        ostream& operator<<(const char *);
inline  ostream& operator<<(const unsigned char *);
inline  ostream& operator<<(const signed char *);
inline  ostream& operator<<(char);
        ostream& operator<<(unsigned char);
inline  ostream& operator<<(signed char);
        ostream& operator<<(short);
        ostream& operator<<(unsigned short);
        ostream& operator<<(int);
        ostream& operator<<(unsigned int);
        ostream& operator<<(long);
        ostream& operator<<(unsigned long);
inline  ostream& operator<<(float);
        ostream& operator<<(double);
        ostream& operator<<(long double);
        ostream& operator<<(const void *);
        ostream& operator<<(streambuf*);
主要討論的是非緣色部份的內容,首先先說明:
inline  ostream& operator<<(char);
inline  ostream& operator<<(signed char);
這兩個的實作內容是:
inline  ostream& ostream::operator<<(char _c) { return operator<<((unsigned char) _c); }
inline  ostream& ostream::operator<<(signed char _c) { return operator<<((unsigned char) _c);}
輸出的格式是一樣的,為什麼呢?當輸出字元時,沒有ASCII是負的字元吧!所以字元以unsigned char格式輸出
再來看
inline  ostream& operator<<(const unsigned char *);
inline  ostream& operator<<(const signed char *);
這兩個實作內容是:
inline  ostream& ostream::operator<<(const unsigned char * _s) { return operator<<((const char *) _s); }
inline  ostream& ostream::operator<<(const signed char * _s) { return operator<<((const char *) _s); }
輸出格式是const char *,目的是輸出以'\0'結尾的字串
ostream operator<<允許輸出變數中的內容,依每個型態的不同輸出不同的格式,但有兩個常用的需要注意:

	ostream& operator<<(const char *);
	ostream& operator<<(const void *);

const char *:它會輸出以'\0'結尾的字串,輸出時會讀取指標所指向的字串值
const void *:它會直接輸出指標的值(即位址),不會讀取指標所指向的內容
似乎有點模糊,沒有關係,看個程式:
	int main()
	{
		int *pInt = 0;
		char *pChar = 0;

		cout<<pInt<<endl
		    <<pChar<<endl;

		return 0;
	}

注意,ostream& operator<<中並沒有char *int *float *double *...等,而是利用現有的candidate。
當使用VC6.0時,輸出應該是:
00000000
接著跳出exception視窗,告訴程式設計師說0x00000000記憶體不能read,為什麼呢?
說明:
int *會被轉換成void *,所以會將pInt內容0當作是位址輸出,所以得到00000000
char *會被轉換成const char *,所以會輸出pChar所指向的字串值,所以會從位址0x00000000開始讀取字串
讀取時,由於位址0x00000000並未授權(unauthorized),所以無法讀取內容,而顯示exception
當欲輸出指標的所指向的位址值時,加上(void *)就可以輸出位址,若沒有加上轉型時,operator <<會選擇適當的
candidate去做輸出的動作。
所以若欲輸出int,float,double等指標的值時,會被轉型成void *
而欲輸出char *指標的值時,會被轉型成const char *,而是輸出指標所指向的字串內容。這需要多加注意。

回目錄
Written By James On 2004/02/08 
Hosted by www.Geocities.ws

1