自定义如下形式的 Point 类,其对象表示平面上的一个点(x, y),通过类成员方式对该类重载二目运算符“十”和“^”,用来求出两个对象的和以及两个对象(平面点)的距离。各运算符的使用含义(运算结果)如下所示:
(1.2,-3.5)+(-1.5,6)=(-0.3,2.5)
(1.2,-3.5)^(-1.5,6)=9.87623
在类外定义类中已声明的函数,并编写主函数,验证所定义函数的正确性。
class Point {
friend ostream & operator<((ostream& os, const Point & p):
friend istream & operator>>(istream & is, Point&p);
public:
Point (double x0 = 0, double y0 =0){x = x0:y = y0;)
Point(const Point & p);
Point operator+(const Point & pt);
double operator^(const Point & pt):
private:
double x,y;
};
求一道关于类和对象的题
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- 技术专家团-小桥流水 2022-03-21 11:29关注
代码及运行结果如下:
#include <iostream> using namespace std; class Point { friend ostream& operator<<(ostream& os, const Point& p); friend istream& operator>>(istream& is, Point& p); public: Point(double x0 = 0, double y0 = 0) { x = x0; y=y0; } Point(const Point& p) { x = p.x; y = p.y; } Point operator-(const Point& pt) { Point pp; pp.x = x - pt.x; pp.y = y - pt.y; return pp; } Point operator +(const Point& pt) { Point pp; pp.x = x + pt.x; pp.y = y + pt.y; return pp; } double operator ^(const Point& pt) { double t = sqrt((x-pt.x) * (x-pt.x) + (y-pt.y) * (y-pt.y)); return t; } private: double x, y; }; ostream& operator<<(ostream& os, const Point& p) { os <<"(" << p.x << "," << p.y<<")"; return os; } istream& operator>>(istream& is, Point& p) { is >> p.x >> p.y; return is; } int main() { Point p1(1.2, -3.5); Point p2(-1.5, 6); Point p3 = p1 + p2; cout <<p1 <<"+" << p2 <<"=" << p3 << endl; double t = p1 ^ p2; cout <<p1 <<"^"<<p2 <<"=" << t << endl; return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 用windows做服务的同志有吗
- ¥60 求一个简单的网页(标签-安全|关键词-上传)
- ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
- ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
- ¥100 为什么这个恒流源电路不能恒流?
- ¥15 有偿求跨组件数据流路径图
- ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
- ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
- ¥15 一直显示正在等待HID—ISP
- ¥15 Python turtle 画图