文档详情

第六章 流类与输入.ppt

发布:2017-08-30约8.01千字共21页下载文档
文本预览下载声明
第六章 流类与输入 / 输出 C++ 中除了可使用C中常见的scanf ( ) ,printf( ) 外,为了适 应OOP ,添加了用于对象I /O 的流类库 ξ6.1流的基本概念 终端 物理设备 磁盘驱动器 抽象为流的逻辑设备 打印机 …… 流 流类 流类库 ξ6.2 流库的基本结构 预定义流 物理设备 ξ6.3 流库中定义的 提取( )和 插入( ) 操作 1. ()提取, 为istream 类,重载各种基本类型 重载函数格式: istream istream::operator ( 参数类型 ) 表明:下列语句可以直接使用,是由于在istream中重载了 istream istream::operator ( int ) int a ; cin a ; ()插入为ostream 类重载了各种基本类型 ostream ostream::operator ( 参数类型 ) , 输入/出,仅适用于已定义的参数类型 若自定义的类对象,(nameclass)就不可直接施 于 cin nameclass 或cout nameclass。 必须对类重载:operator (…) 或 operator (…) 。且只能 重载为友元函数。 例(1)类矩形Rectangle,以友元函数重载 ,作类对象输出. #include iostream.h class Rectangle { private : int width ; int height ; public : Rectangle ( int w , int h ) { width = w ; height = h ; } friend ostream operator ( ostream stream , Rectangle ob ) ; friend istream operator ( istream stream, Rectangle ob ); } ; ostream operator ( ostream stream , Rectangle ob ) { stream “宽:” ob.width endl ; stream “高:” ob.height endl ; return stream ; } istream operator ( istream stream, Rectangle ob ) //返回类型 不变的第一参数 变化的第二参数,必须为对象引用 { cout “请输入矩形的宽:” ; stream ob.width ; cout “请输入矩形的高:” ; stream ob.height ; return stream ; } void main ( ) { Rectangle ob ( 10, 20 ) ; cout ob ; // operator (cout, ob )实参调用 cin ob ; // operator ( cin, ob ) 实参调用 cout ob ; } 分析可知: (1) , 只能重载为类的友元函数 (2)对于输出 , operator ( ) 返回类型是ostream类引用, 以便在一条cout语句中可作多个对象的输出。 (3)对于输出 , 第一参数必须为对象ostream引用, 否则,若是 传值方式,由于函数返回的是局部对象参数的引用,故出错。 (4)对于输出 ,为提高效率,第二参数可用引用 (5)operator ( )
显示全部
相似文档