定义一个点类Point,该类有两个int型的私有数据成员x,y(分别代表x坐标与y坐标)。现在要求对Circle类重载“+”运算符,要求如下:
(1)先将“+”重载为Point类的非成员函数,其语义是求两个点之间的直线距离;
(2)再将“+”重载为Point类的成员函数,其语义是当前Point对象的x和y坐标分别加上一个同样的int型值,使当前的点坐标被修改(例如点[3,5] + 3的结果是得到点[6,8]);
(3)为了方便输出,对Point类重载“<<”运算符,用于输出Point对象的坐标;
(4)为该类定义你认为必要的其他成员;
(5)在主函数中对以上重载后的运算符函数进行测试。
int main(){
int x,y;
cin>>x>>y;
Point p1(x,y);
cin>>x>>y;
Point p2(x,y);
cout<<"Distance between p1"< cout< return 0; } 输入描述 分两行输入两个点的坐标 输出描述 按样例格式输出数据 提示 你需要提交除main函数之外的代码 样例输入 1 2 样例输出 Distance between p1[1,2] and p2[3,4] is 2.82843 #include 欢迎分享,转载请注明来源:内存溢出
3 4
[4,5] [8,9]
#include
#include
using namespace std;
class Point {
private:
int x;
int y;
public:
Point(){}
Point(int x, int y)
{
this->x = x;
this->y = y;
}
Point(const Point& p)
{
x = p.x;
y = p.y;
}
int getX() { return x; }
int getY() { return y; }
friend double operator+(const Point& c1, const Point& c2)
{
double x = static_cast
double y = static_cast
double len = sqrt(x * x+ y * y);
return len;
}
Point operator+(const int t)
{
Point c;
c.x = x + t;
c.y = y + t;
return c;
}
friend ostream& operator<<(ostream& out, const Point& p)
{
out << "[" << p.x << "," << p.y << "]";
return out;
}
};
评论列表(0条)