码迷,mamicode.com
首页 > 其他好文 > 详细

ostream类重载的operator<<()函数

时间:2015-05-10 11:23:30      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

 

ostream类重载的operator<<()函数

标签:

原文地址:http://www.cnblogs.com/kevinq/p/4491807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!