19.21/0标准流类例19-3:分析语句cout<<"My nameis Jone" ;分析:1、cout是ostream对象:2、<<是操作符;3、右面的字符串是char*类型;4、所以,匹配ostream& operator<< (ostream& dest, char * pSource);5、将整个字符串输出,并返回ostream流对象的引用
例19-3:分析语句 cout << " My name is Jone " ; 分析: 1、cout是ostream对象; 2、<<是操作符; 3、右面的字符串是char * 类型; 4、所以,匹配 ostream& operator << ( ostream& dest, char * pSource) ; 5、将整个字符串输出,并返回ostream流对象的引用
19.21/0标准流类例19-3:分析语句cout<<" this is " << 7 ;分析:1、根据<<的运算优先级,可以看作:(cout<<" this is ")<< 7 ;2、由于“cout<<”thisis“”返回ostream流对象的引用,与后面的<<7匹配了另一个ostream& operator<<(ostream& dest, int source);3、结果构成了连续的输出
例19-3:分析语句 cout << " this is " << 7 ; 分析: 1、根据<<的运算优先级,可以看作: (cout << " this is " ) << 7 ; 2、由于“cout << ” this is “ ”返回ostream流对象的引 用,与后面的 << 7匹配了另一个 ostream& operator << ( ostream& dest, int source) ; 3、结果构成了连续的输出
19.21/0标准流类 cin是istream流类的全局对象,istream流类也有若干个友元:istream& operator >>(istream& dest, char * pSource);istream& operator >>(istream& dest, int source);istream& operator >>(istream& dest, char source);// 等等;流提取运算符(>>):重载右移位运算符表示流的输入
• cin是istream流类的全局对象。 • istream流类也有若干个友元: istream& operator >> ( istream& dest, char * pSource) ; istream& operator >> ( istream& dest, int source) ; istream& operator >> ( istream& dest, char source) ; // 等等 ; • 流提取运算符(>>):重载右移位运算符表示 流的输入
19.21/0标准流类ch19 1.cpp:除法操作不能进行时显示一条错误信息#include<iostream>using namespace std;void fn(int a,int b )1if (b == 0)cerr<<" zero encountered."<<" The message cannot be redirected.In";elsecout<<a / b<<endl;运行结果:void main()[10fn(20,2);fn(20,0);zero encountered.The message cannot1Jberedirected
ch19_1.cpp:除法操作不能进行时显示一条错误信息 #include<iostream> using namespace std ; void fn( int a , int b ) { if ( b == 0) cerr << " zero encountered. " << " The message cannot be redirected.\n " ; else cout << a / b << endl ; } void main( ) { fn ( 20 , 2 ) ; fn ( 20 , 0 ) ; } 运行结果: 10 zero encountered. The message cannot be redirected
19.21/0标准流类主函数第一次调用fn(20,2);时,没有碰到除0运算。得到20/2的计算结果为10第二次调用fn(20,0);时,碰到了除0运算。于是,在屏幕上输出错误信息也就是,写到cerr上的信息是不能被重定向的,只能输出到屏幕
• 主函数第一次调用fn(20 , 2); 时,没有碰到除 0运算。 • 得到20 / 2 的计算结果为10。 • 第二次调用fn(20 , 0); 时,碰到了除0运算。 • 于是,在屏幕上输出错误信息。 • 也就是,写到cerr上的信息是不能被重定向 的,只能输出到屏幕