先定义一个点类 Point ,再由点类 Point 派生出线段类 Line ,在主函数中定义 一个线段类对象,调用成员函数求出改线段的长度和其中点坐标。 (类中的数据成员不能定义为 public 。
时间: 2024-05-27 10:13:50 浏览: 120
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x, y;
public:
Point(double x = 0, double y = 0) : x(x), y(y) {}
double getX() const { return x; }
double getY() const { return y; }
};
class Line : public Point {
private:
Point p1, p2;
public:
Line(double x1, double y1, double x2, double y2) : p1(x1, y1), p2(x2, y2) {}
double getLength() const { return sqrt(pow(p1.getX() - p2.getX(), 2) + pow(p1.getY() - p2.getY(), 2)); }
Point getMidPoint() const { return Point((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2); }
};
int main() {
Line line(0, 0, 3, 4);
cout << "Length: " << line.getLength() << endl;
Point midPoint = line.getMidPoint();
cout << "Mid Point: (" << midPoint.getX() << ", " << midPoint.getY() << ")" << endl;
return 0;
}
阅读全文