文档详情

面向对象程序设计与C++语言 第二版 教学课件 作者 杨庚 王汝传 叶晓国 第十二讲.ppt

发布:2017-08-15约5.22千字共18页下载文档
文本预览下载声明
* * 1. ios 流库的结构: istream 和 ostream 2. 流对象cin一般指键盘。  流对象cout一般指屏幕。 3.输入/输出格式控制的方法:   ? 使用ios 的成员函数   ? 使用操作函数 cin.getline(buffer, SIZE); cout.width(10); cout setw(10) x; cout setw(10) setfill(* ) x; 。 输出与输入 用户自定义类型的输入/输出 文件的输入/输出 输入/输出流库 用户自定义类型的输入/输出 自定义输入/输出类型的目的 使用户能使用简洁、有效、便利的方法输入/输出特殊结构的数据, 如:电话号码:025-3498888 三维点的坐标:(1,2,3) 实现自定义输入/输出类型的手段 通过对输入 (?)和输出(?)运算符的重载,定义特殊的输入/输出结构 例1:电话号码的输入/输出 #include iostream.h class PhoneNumber { friend ostream operator (ostream , const PhoneNumber ); //重载输出运算符 friend istream operator (istream , PhoneNumber ); //重载输入运算符 private: char areaCode[4], exg[4], line[5]; }; ostream operator (ostream output, const PhoneNumber num) { output num.areaCode - num.exg - line; return output; // 此语句的目的:实现cout a b c; } istream operator (istream input, PhoneNumber num) { input.getline(num.areaCode,4); //读入地区号 input.ignore( ); //跳过横线- input.getline(num.exg,4); input.getline(num.line,5); return input; // 此语句的目的:实现 in a b c; } 用户自定义类型的输入/输出 例1:电话号码的输入/输出(续) void main( ) { PhoneNumber phone; //定义一个对象实例phone cout Enter a phone number in the form 025-3493333: endl; cin phone; //应用重载的输入运算符读入自定义的类型数据 cout The phone number entered was : endl phone endl; //应用重载的输出运算符写出自定义的类型数据 } 结果: Enter a phone number in the form 025-3493333: 025-3492470 The phone number entered was : 025-349-2470 用户自定义类型的输入/输出 例2:圆的相关数据的输出 #include iostream.h class Circle { friend ostream operator (ostream , const Circle ); //重载输出运算符 public: Circle(float a, float b, float c){ radius=a; x=b; y=c;} private: float radius; //圆的半径 float x, y; //圆心的坐标 }; ostream operator (ostream output, const Circle C) { output Center= [ C.x , C.y ]; endl Radius = C.radius endl; retu
显示全部
相似文档