ostream類重載了operator<<()以識別不同的類型,如:
int short long unsigned int unsigned short unsigned long
float double long double char signed char unsigned char
這樣cout就不用像C語言中的printf那樣需要程序員自行匹配數據類型,如:printf("%s%d%f","hello world",32,3.1415)
由於C++用指向字符串位置的指針來表示字符串,因此ostream類重載了char型指針類型的插入運算符<<,即:
ostream& operator<<(void*);
ostream& operator<<(const char*);
ostream& operator<<(const signed char*);
ostream& operator<<(const unsigned char*);
后三種形式分別接受3種char型常指針,輸出char型常指針指向的內容,直到遇到字符串結束符'\0',如:
char *ch1="hello world"
char ch2[12]="hello world"
cout<<ch1<<ch2<<endl;
即會調用兩次ostream& operator<<(const char*)
而第一種形式則是用來輸出任何類型的地址,如:
int a=3;
cout<<&a<<endl;
就會調用ostream& operator<<(void*)來輸出a的地址。
由於字符串是指向第一個字符的指針,因此要獲取字符串的地址,就需要將char*型指針強制轉換為void*,然后才能調用operator(void*)來
輸出字符串地址,否則調用的則是operator(const char*),輸出的則是char型常指針指向的內容,如:
char *ch="hello world";
char s[12]="hello world";
cout<<ch<<endl; //調用operator<<(const char*)輸出字符串
cout<<(void*)ch<<endl; //調用operator<<(void*)輸出字符串地址
cout<<s<<endl; //調用operator<<(const char*)輸出字符串
cout<<(void*)s<<endl; //調用operator<<(void*)輸出字符串地址
#include <iostream> using namespace std; int main() { int a=3; int *p=&a; cout<<p<<endl; //0x22fe98 cout<<&a<<endl; //0x22fe98 char *ch="hello world"; cout<<ch<<endl; //hello world cout<<(void*)ch<<endl; //輸出字符串ch的地址0x47f000 cout<<&ch<<endl; //輸出指針ch的地址0x22fe94 char s[12]="hello world"; cout<<s<<endl; //hello world cout<<(void*)s<<endl; //輸出字符串s的地址0x22fe88 cout<<&s<<endl; //輸出字符串s的地址0x22fe88(因為&s是個行指針) return 0; }