二维坐标Point类派生三维空间坐标点类Point3D.cpp 800 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. class Point {
  5. protected:
  6. double x, y;
  7. public:
  8. Point() : x(0), y(0) {}
  9. Point(double x, double y) : x(x), y(y) {}
  10. double getx() {
  11. return x;
  12. }
  13. double gety() {
  14. return y;
  15. }
  16. double dist(const Point& p) {
  17. return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
  18. }
  19. };
  20. class Point3D : public Point {
  21. private:
  22. double z;
  23. public:
  24. Point3D() : Point(), z(0) {}
  25. Point3D(double x, double y, double z) : Point(x, y), z(z) {}
  26. double getz() {
  27. return z;
  28. }
  29. double dist(const Point3D& p) {
  30. return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y) + (z - p.z) * (z - p.z));
  31. }
  32. };
  33. int main() {
  34. Point3D A;
  35. Point3D B(4, 5.6, 7.8);
  36. double distance = A.dist(B);
  37. cout << "|A-B|=" << distance << endl;
  38. return 0;
  39. }