面向对象实验四(输入输出流)

一、实验目的
1、掌握用户自定义类型的输入输出。
2、掌握文件的输入、输出。

 

二、实验内容
1、定义一个复数类,并为其重载>>和<<运算符,使得复数对象可以整体输入输出,并给出main()对该类进行应用。

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 //复数类
 6 class complex
 7 {
 8 private:
 9     float real;
10     float imag;
11 public:
12     friend istream &operator>>(istream &in,class complex &temple);//重载输入运算符
13     friend ostream &operator<<(ostream &out,class complex &temple);//重载输出运算符
14 };
15 int main()
16 {
17     int i;
18     complex obj;
19     for(i=0;i<4;i++)
20     {
21         cout<<"请输入复数的实部和虚部:";
22         cin>>obj;
23         cout<<obj;
24     }
25     return 0;
26 }
27 
28 //重载输入运算符
29 istream &operator>>(istream &in,class complex &temple)
30 {
31     in>>temple.real;
32     in>>temple.imag;
33     return in;
34 }
35 
36 //重载输出运算符
37 ostream &operator<<(ostream &out,complex &temple)
38 {
39     out<<endl;
40     out<<temple.real;
41     if(temple.imag>0)
42     {
43         out<<'+';
44     }
45     out<<temple.imag<<'i'<<endl;
46     return out;
47 }

 

2、定义空间中的点类(有x,y,z坐标),并重载其>>和<<运算符。编写主函数完成从键盘上读入10个点的坐标,写入数据文件(point.data)中,从数据文件(point.data)中读入并显示在标准输出设备上。

 1 #include<iostream>
 2 #include<fstream>
 3 #define MAX 10
 4 
 5 using namespace std;
 6 
 7 //点类
 8 class point
 9 {
10 public:
11     float x;
12     float y;
13     float z;
14     friend istream& operator>>(istream& in,point &temple);//重载输入运算符
15     friend ostream& operator<<(istream& out,point &temple);//重载输出运算符
16 };
17 
18 int main()
19 {
20     int i;
21     point obj[MAX];
22     cout<<"请输入10个点的坐标:"<<endl;
23     for(i=0;i<MAX;i++)
24     {
25         cin>>obj[i];
26     }
27     ofstream out("point.data");//打开输出文件流
28     if(out)//如果打开成功
29     {
30         for(i=0;i<MAX;i++)//向文件输入信息
31         {
32             out<<obj[i].x<<' ' <<obj[i].y<<' '<<obj[i].z<<endl;
33         }
34         out.close();//关闭
35     }
36     cout<<endl<<"10个点的坐标分别为:"<<endl;
37     ifstream in("point.data");//打开输入文件流
38     if(in)//如果打开成功
39     {
40         for(i=0;i<MAX;i++)//从文件读取信息
41         {
42             in>>obj[i].x>>obj[i].y>>obj[i].z;
43             cout<<'('<<obj[i].x<<','<<obj[i].y<<','<<obj[i].z<<')'<<endl;//显示
44         }
45         in.close();//关闭
46     }
47     return 0;
48 }
49 
50 //重载输入运算符
51 istream& operator>>(istream& in,point &temple)
52 {
53     in>>temple.x>>temple.y>>temple.z;
54     return in;
55 }
56 
57 //重载输出运算符
58 ostream& operator<<(ostream& out,point &temple)
59 {
60     out<<temple.x<<temple.y<<temple.z;
61     return out;
62 }

 

转载于:https://www.cnblogs.com/xautlmx/p/3441394.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值