2、设计一个名为Point2D的类,表示平面坐标下的一个点,这个类包括:
两个double型数据成员:x, y,分别表示横坐标和纵坐标
一个带形参的构造函数:Point2D(double x, double y)
成员函数double dist(const Point2D &),返回当前点与给定点的距离
设计一个名为Point3D的类,表示三维空间的一个点,这个类包括:
三个double型数据成员: x, y, z,代表点的坐标
一个带形参的构造函数:Point3D(double x, double y, double z)
成员函数double dist(const Point3D &),返回当前点与给定点的距离
定义一个模板函数double mydist(T1 & x, T1 & y),使得他既可以计算两个Point2D对象之间的距离,
也可以计算两个Point3D对象之间的距离。
实现上面两个类和模板函数,并在主函数中测试:
创建A1(1.2,3.4),A2(5.6,7.8) 和B1(1.2,3.4,5.6), B2(9.8,7.6,5.4),并调用模板函数mydist
输出A1,A2之间的距离和B1,B2之间的距离。
(程序取名为hw14_02.cpp)
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
public:
Point() {
x=0;y=0;
}
Point(double x, double y) {
this->x=x; this->y=y;
}
double dist(const Point& p) const {
return pow(pow(x-p.x,2)+pow(y-p.y,2),0.5);
}
private:
double x,y;
};
class Point3D : public Point
{
public:
Point3D() {z=0;}
Point3D(double x, double y, double z) : Point(x,y) {this->z=z;}
double dist(const Point3D& p) const {
return pow(pow(Point::dist(p),2)+pow(z-p.z,2),0.5);
}
private:
double z;
};
template <typename T1>
double mydist(T1 & x, T1 & y) {
return x.dist(y);
}
int main()
{
Point A1(1.2,3.4),A2(5.6,7.8);
Point3D B1(1.2,3.4,5.6), B2(9.8,7.6,5.4);
cout<<"Point:"<<mydist(A1,A2)<<endl;
cout<<"Point3D:"<<mydist(B1,B2)<<endl;
return 0;
}
Post Views: 9