4.5流插入运算符和流提取运算符的重载
流插入运算符和流提取运算符的重载:问题
cout << 5 << “this”; 为什么能够成立?
cout是什么? “<<” 为什么能用在 cout上?
流插入运算符的重载:
cout 是在 iostream 中定义的,ostream 类 的对象。
“<<” 能用在cout 上是因为,在iostream 里对 “<<” 进行了重载。
考虑,怎么重载才能使得 cout << 5; 和 cout << “this”都能成立 ?
流插入运算符的重载 :
有可能按以下方式重载成 ostream类的成员函数:
void ostream::operator<<(int n) { …… //输出n的代码 return; }
流插入运算符的重载 cout << 5 ; 即 cout.operator<<(5); cout << “this”; 即 cout.operator<<( “this” ); 怎么重载才能使得 cout << 5 << “this” ; 成立?
流插入运算符的重载 cout << 5 << “this”; 本质上的函数调用的形式是什么? cout.operator<<(5).operator<<(“this”);
流插入运算符的重载 ostream & operator<<( ostream & o,const CStudent & s){ o << s.nAge ; return o; }
假定c是Complex复数类的对象,现在希望 写“cout << c;”,就能以“a+bi”的形 式输出c的值,写“cin>>c;”,就能从键 盘接受“a+bi”形式的输入,并且使得 c.real = a,c.imag = b。
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.