好文档 - 专业文书写作范文服务资料分享网站

实验四 流运算符的重载及文件的使用

天下 分享 时间: 加入收藏 我要投稿 点赞

实 验 报 告

( 2014 / 2015 学年 第 二 学期)?

???

课程名称 实验名称

面向对象程序设计及C++ 实验四:流运算符的重载及文件的使用

实验时间 2016

指导单位 计算机研究中心 指导教师 陈景强

年 5 月 30 日

学生姓名 学院(系)

班级学号 专 业

实 验 报 告

实验名称 流运算符的重载及文件的使用 指导教师 陈景强 实验类型 验证 实验学时 2 实验时间 4 一、 实验目的和要求 (1)掌握在自定义的类中重载输入流运算符>>和输出流运算符<<,并输入/输出本类对象。 (2)掌握文件操作的步骤和方法,能利用程序建立数据文件、打开数据文件并进行相关操作。 二、实验环境(实验设备) 硬件: 微型计算机 软件: Microsoft Visual C++6.0 三、实验原理及内容 实验题目(1): 在多态性实验第2题的基础上,在复数类中增加输入流运算符>>和输出流运算符<<的重载,主函数通过“cin>>对象名”输入对象的值,通过“cout<<对象名”输出对象的值,输出复数值时将原来主函数中“对象名.print( )”改成“cout<<对象名”形式。 在上一步完成的基础上,将复数类改成一个类模板,只设一个模板参数,即实部和虚部用同一种类型,修改相应的代码,完成输入、输出功能。 实验解答: (1)源代码参考多态性实验第2题。 (2)记录重载operator<<函数的代码: ostream& operator<<(ostream &s,const Complex &c) { cout<0)cout<<\ cout<

(3) 将类改写成类模板:(多态性实验代码中的重载符号仅保留加法+,其他可省略)#include using namespace std; template class Complex { private: T real; T imag; public: Complex(T r=0,T i=0) { real=r; imag=i; } friend Complex operator+(const Complex &a,const Complex &b); friend Complex operator-(const Complex &a,const Complex &b); friend ostream &operator<<(ostream &out,const Complex &a); friend istream &operator>>(istream &in,const Complex &a); Complex operator*(const Complex &a); Complex operator/(const Complex &a); }; template ostream &operator<<(ostream &out,const Complex &a) { out<0) out<<\ out< istream &operator>>(istream &in,const Complex &a) { in>>a.real; if(a.imag!=0) 2

{ if(a.imag>0) in>>\ in>>a.imag>>\ } return in; } template Complex operator+(const Complex &a,const Complex &b) { Complex temp; temp.real=a.real+b.real; temp.imag=a.imag+b.imag; return temp; } template Complex operator-(const Complex &a,const Complex &b) { Complex temp; temp.real=a.real-b.real; temp.imag=a.imag-b.imag; return temp; } template Complex Complex ::operator*(const Complex &a) { Complex temp; temp.real=real*a.real; temp.imag=imag*a.imag; return temp; } template Complex Complex ::operator/(const Complex &a) { Complex temp; temp.real=real/a.real; temp.imag=imag/a.imag; return temp; } void main() { Complex a1,a2,a3,a4,a5,a6; cout<<\ cin>>a1; 3

cout<<\ cin>>a2; cout<<\ cout<<\ a3=a1+a2; cout<<\ a4=a1-a2; cout<<\ a5=a1*a2; cout<<\ a6=a1/a2; cout<<\} 实 验 报 告

4

实验四 流运算符的重载及文件的使用

实验报告(2014/2015学年第二学期)????课程名称实验名称面向对象程序设计及C++实验四:流运算符的重载及文件的使用实验时间2016指导单位计算机研究中心指导教师陈景强年5月30日
推荐度:
点击下载文档文档为doc格式
2d6cw9m4f034ka295j7z7yqpo85se700d72
领取福利

微信扫码领取福利

微信扫码分享