C++定义二维座标上的点point类,包含有横坐标和纵坐标等属性,编写对这些属性进行操作的方法

2024-12-02 13:28:30
推荐回答(1个)
回答1:

#include
using std::cout;
using std::endl;
using std::ostream;

#include

class point {
public:
point(double x = 0, double y = 0) : cx(x), cy(y) {}
point(const point &p) : cx(p.cx), cy(p.cy) {}
double get_center_x() const { return cx; }
void set_center_x(double x) { cx = x; }
double get_center_y() const { return cy; }
void set_center_y(double y) { cy = y; }
private:
double cx, cy;
};

class line {
friend ostream & operator<< (ostream &out, const line &l);
public:
line(const point &x, const point &y) : p1(x), p2(y) {}
double length() const {
double dx = p1.get_center_x() - p2.get_center_x();
double dy = p1.get_center_y() - p2.get_center_y();
return sqrt(dx * dx + dy * dy);
}
private:
point p1, p2;
};

ostream & operator<< (ostream &out, const point &p) {
out << "(" << p.get_center_x() << ", " << p.get_center_y() << ")";
return out;
}

ostream & operator<< (ostream &out, const line &l) {
out << l.p1 << ", " << l.p2 << "\tLength: " << l.length();
return out;
}

int main() {
point p1(1, 2);
point p2(p1);
p2.set_center_x(3);
p2.set_center_y(4);

line l(p1, p2);
cout << l << endl;

return 0;
}