自定义如下形式的 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 Vue3 大型图片数据拖动排序
- ¥15 划分vlan后不通了
- ¥15 GDI处理通道视频时总是带有白色锯齿
- ¥20 用雷电模拟器安装百达屋apk一直闪退
- ¥15 算能科技20240506咨询(拒绝大模型回答)
- ¥15 自适应 AR 模型 参数估计Matlab程序
- ¥100 角动量包络面如何用MATLAB绘制
- ¥15 merge函数占用内存过大
- ¥15 使用EMD去噪处理RML2016数据集时候的原理
- ¥15 神经网络预测均方误差很小 但是图像上看着差别太大