重载提取(>>)和插入(<<)运算符,使其可以实现“点”对象的输入和输出,并利用重载后的运算符,从键盘读入点坐标,写到磁盘文件point.txt中。用C++
时间: 2023-12-03 10:45:10 浏览: 40
下面是一个实现点对象输入输出的样例代码,其中将点的坐标以“x,y”的形式输入输出:
```cpp
#include <iostream>
#include <fstream>
using namespace std;
class Point {
public:
Point(int x, int y) : x(x), y(y) {}
friend ostream& operator<<(ostream& os, const Point& p) {
os << p.x << "," << p.y;
return os;
}
friend istream& operator>>(istream& is, Point& p) {
char comma;
is >> p.x >> comma >> p.y;
return is;
}
private:
int x, y;
};
int main() {
// 从键盘读入点坐标,写到磁盘文件point.txt中
ofstream fout("point.txt");
Point p(0, 0);
while (cin >> p) {
fout << p << endl;
}
fout.close();
// 从磁盘文件point.txt中读入点坐标,输出到屏幕上
ifstream fin("point.txt");
while (fin >> p) {
cout << p << endl;
}
fin.close();
return 0;
}
```
在该代码中,我们通过重载输入输出运算符`>>`和`<<`,来实现点对象的输入和输出。同时,我们利用文件流`ofstream`和`ifstream`来读写磁盘文件。最终,我们可以通过从键盘读入点坐标,将其写入磁盘文件中;或者从磁盘文件中读入点坐标,将其输出到屏幕上。