自定义如下形式的 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;
};
代码及运行结果如下:
#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.2,-3.5)+(-1.5,6)=-0.3,2.5)
(1.2,-3.5)^-1.5,6)-9.87623
===
这写的正确吗?括号都不匹配啊
double operator"(const Point & pt):----这是啥操作符啊??
也没看到 operator + 和 opreator ^