重载流插入运算符和流提取运算符

流插入运算符:“<<”

流提取运算符:“>>”

cout 是在 iostream 中定义的,ostream 类的对象。

“<<” 能用在cout 上是因为,在iostream里对 “<<” 进行了重载。

怎么重载才能使得cout << 5; 和 cout << “this”都能成立?

ostream & ostream::operator<<(int n)
{
…… //输出n的代码
return * this;
}
ostream & ostream::operator<<(const char * s )
{
…… //输出s的代码
return * this;
}

cout << 5 << “this”;

本质上的函数调用的形式是什么?

cout.operator<<().operator<<(“this”);

Question:

假定c是Complex复数类的对象,现在希望写“cout << c;”,就能以“a+bi”的形式输出c的值,写“cin>>c;”,就能从键盘接受“a+bi”形式的输入,并且使得c.real = a,c.imag = b。

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Complex {
  double real,imag;
public:
Complex( double r=, double i=):real(r),imag(i){ };
friend ostream & operator<<( ostream & osconst Complex & c);
friend istream & operator>>( istream & is,Complex & c);
};
ostream & operator<<( ostream & os,const Complex & c)
{
  os << c.real << "+" << c.imag << "i"; //以"a+bi"的形式输出
  return os;
}
istream & operator>>( istream & is,Complex & c)
{
  string s;
  is >> s; //将"a+bi"作为字符串读入, “a+bi” 中间不能有空格
  int pos = s.find("+",);
  string sTmp = s.substr(,pos); //分离出代表实部的字符串
  c.real = atof(sTmp.c_str()); //atof库函数能将const char*指针指向的内容转换成 float
  sTmp = s.substr(pos+, s.length()-pos-); //分离出代表虚部的字符串
  c.imag = atof(sTmp.c_str());
  return is;
}
int main()
{
  Complex c;
  int n;
  cin >> c >> n;
  cout << c << "," << n;
  return ;
}

运行结果可以如下:

13.2+133i 87↙

13.2+133i, 87

最新文章

  1. SharePoint 2013 入门教程
  2. EF不能很好的支持DDD?估计是我们搞错了!
  3. RecylerView完美实现瀑布流效果
  4. SQL复制一个表的数据到另一个表
  5. 第二篇 Replication:分发服务器的作用
  6. jquery函数
  7. Missing artifact com.sun:tools:jar:1.5.0:system 补充
  8. [iOS微博项目 - 3.4] - 获取用户信息
  9. hung_task_timeout_secs 和 blocked for more than 120 seconds
  10. php下载文件的代码示例
  11. NGUI系列教程二
  12. Linux入门基础 #10:命令行文本处理工具
  13. eclipse android ndk 提示Type &#39;JNIEnv&#39; could not be resolved 等信息解决办法
  14. Android原生Cling演化的覆盖层
  15. 每天一道Java题[10]
  16. //读取配置文件(属性文件)的工具类-ConfigManager
  17. Linux学习笔记-林耐斯Notes-Linux就该这么学
  18. vim 命令整理(自己经常使用)
  19. python的序列类
  20. 使用numba加速python程序

热门文章

  1. nginx访问目录是没加/的重定向控制
  2. Mybatis的逆向工程以及Example的实例函数及详解
  3. day11 作业
  4. 夯实Java基础(二十四)——Java8新特征之Optional类
  5. Elasticsearch 如何使用RESTful API
  6. 第1节 Scala基础语法:3、环境;4、插件
  7. postInvalidate 解决View.GONE,没有刷新的问题
  8. RIFF
  9. PHP中的异常知识
  10. Adroid ViewPage+GridView实现每页6个元素,三页滑动切换