题目要求定义一个point类,包含数据成员x和y。要求重载运算符“<<”,cin>>。p2>>p3,cout<<p2,p3
时间: 2024-03-16 11:46:31 浏览: 32
好的,这是一个经典的面向对象编程题目,下面是定义point类并重载运算符的代码:
```c++
#include <iostream>
using namespace std;
class point{
public:
int x, y;
friend istream& operator>>(istream& in, point& p){
in >> p.x >> p.y; // 重载输入运算符
return in;
}
friend ostream& operator<<(ostream& out, const point& p){
out << "(" << p.x << "," << p.y << ")"; // 重载输出运算符
return out;
}
};
int main(){
point p1, p2, p3;
cout << "Please input p1's coordinate (x, y): ";
cin >> p1;
cout << "Please input p2's coordinate (x, y): ";
cin >> p2;
cout << "Please input p3's coordinate (x, y): ";
cin >> p3;
cout << "p2: " << p2 << endl;
cout << "p3: " << p3 << endl;
return 0;
}
```
在这个代码中,point类包含了两个数据成员 x 和 y,还重载了输入和输出运算符,分别使用 istream 和 ostream 的引用作为输入和输出的流对象,这样就可以通过 cin 和 cout 实现输入和输出 point 类对象的操作。在主函数中,我们定义了三个 point 类对象 p1、p2 和 p3,使用 cin 输入 p1、p2 和 p3 的坐标,然后使用 cout 输出 p2 和 p3 的坐标。
其中输入运算符的重载使用了友元函数,因为我们需要访问类的私有数据成员 x 和 y,同时重载输出运算符的实现也使用了友元函数,因为我们需要在输出时对输出的格式进行处理。
希望这段代码可以帮到你,如果你还有其他问题,请随时提出。