面向对象实验四(输入输出流)
来源:互联网 发布:java开发有哪些方向 编辑:程序博客网 时间:2024/06/05 01:10
一、实验目的
1、掌握用户自定义类型的输入输出。
2、掌握文件的输入、输出。
二、实验内容
2、定义空间中的点类(有x,y,z坐标),并重载其>>和<<运算符。编写主函数完成从键盘上读入10个点的坐标,写入数据文件(point.data)中,从数据文件(point.data)中读入并显示在标准输出设备上。
1、掌握用户自定义类型的输入输出。
2、掌握文件的输入、输出。
二、实验内容
1、定义一个复数类,并为其重载>>和<<运算符,使得复数对象可以整体输入输出,并给出main()对该类进行应用。
#include<iostream>using namespace std;//复数类class complex{private: float real; float imag;public: friend istream &operator>>(istream &in,class complex &temple);//重载输入运算符 friend ostream &operator<<(ostream &out,class complex &temple);//重载输出运算符};int main(){ int i; complex obj; for(i=0;i<4;i++) { cout<<"请输入复数的实部和虚部:"; cin>>obj; cout<<obj; } return 0;}//重载输入运算符istream &operator>>(istream &in,class complex &temple){ in>>temple.real; in>>temple.imag; return in;}//重载输出运算符ostream &operator<<(ostream &out,complex &temple){ out<<endl; out<<temple.real; if(temple.imag>0) { out<<'+'; } out<<temple.imag<<'i'<<endl; return out;}
2、定义空间中的点类(有x,y,z坐标),并重载其>>和<<运算符。编写主函数完成从键盘上读入10个点的坐标,写入数据文件(point.data)中,从数据文件(point.data)中读入并显示在标准输出设备上。
#include<iostream>#include<fstream>#define MAX 10using namespace std;//点类class point{public: float x; float y; float z; friend istream& operator>>(istream& in,point &temple);//重载输入运算符 friend ostream& operator<<(ostream& out,point &temple);//重载输出运算符};int main(){ int i; point obj[MAX]; cout<<"请输入10个点的坐标:"<<endl; for(i=0;i<MAX;i++) { cin>>obj[i]; } ofstream out("point.data");//打开输出文件流 if(out)//如果打开成功 { for(i=0;i<MAX;i++)//向文件输入信息 { out<<obj[i].x<<' ' <<obj[i].y<<' '<<obj[i].z<<endl; } out.close();//关闭 } cout<<endl<<"10个点的坐标分别为:"<<endl; ifstream in("point.data");//打开输入文件流 if(in)//如果打开成功 { for(i=0;i<MAX;i++)//从文件读取信息 { in>>obj[i].x>>obj[i].y>>obj[i].z; cout<<'('<<obj[i].x<<','<<obj[i].y<<','<<obj[i].z<<')'<<endl;//显示 } in.close();//关闭 } return 0;}//重载输入运算符istream& operator>>(istream& in,point &temple){ in>>temple.x>>temple.y>>temple.z; return in;}//重载输出运算符ostream& operator<<(ostream& out,point &temple){ out<<temple.x<<temple.y<<temple.z; return out;}
- 面向对象实验四(输入输出流)
- C++面向对象实验(四)
- 面向对象(四)
- 面向对象(四)
- C++面向对象实验四:超市管理系统
- 面向对象表达式(四)
- 面向对象PHP(四)
- 面向对象基础(四)
- 面向对象高级(四)
- (四)面向对象编程
- C++面向对象实验(一)
- C++面向对象实验(二)
- C++ 面向对象实验(三)
- C++面向对象实验(五)
- 面向对象第一次实验
- 面向对象第二次实验
- 面向对象第三次实验
- 面向对象实验
- printk 使用方法
- SQLite适用的范围
- 常见的Java问题排查方法
- printf("good bye my last regional\n"); //ACM退役贴
- 使用Jquery进行select的级联操作
- 面向对象实验四(输入输出流)
- Mac&iOS Socket编程
- 由运放组成的V-I、I-V转换电路
- dede 列表页标签 (也就是分页显示数据)
- SQLite 第三版总览
- 10个迷惑新手的Cocoa&Objective-c开发问题
- 【黑马程序员】 学习笔记 - 直击7K面试题 - 张孝祥老师的银行业务调度管理系统
- vs编译器设置
- 自创小说《彩虹雨》 连载(一)