C++编写一个Point点类该类有x和y属性分别表示横坐标值和纵坐标值。在该类中重载+运算符功能是将两个点对象的横纵坐标值分别相加得到一个新的点对象的坐标值并返回这个新的点对象。重载-运算符功能是计算两个点之间的距离。
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x;
double y;
public:
Point(double xval=0, double yval=0):x(xval), y(yval){}
Point operator+ (const Point& p) const {
return Point(x + p.x, y + p.y);
}
double operator- (const Point& p) const {
double dx = x - p.x;
double dy = y - p.y;
return sqrt(dx*dx + dy*dy);
}
void setX(double xval) { x = xval; }
void setY(double yval) { y = yval; }
double getX() const { return x; }
double getY() const { return y; }
};
int main() {
Point p1(1, 2);
Point p2(3, 4);
Point p3 = p1 + p2;
cout << "p3: (" << p3.getX() << ", " << p3.getY() << ")" << endl;
double dist = p1 - p2;
cout << "Distance: " << dist << endl;
return 0;
}
输出结果为:
p3: (4, 6)
Distance: 2.82843
``
原文地址: https://www.cveoy.top/t/topic/eGtE 著作权归作者所有。请勿转载和采集!