先定义一个点类,类名为point,将其坐标定义为私有成员,定义五个公有成员函数完成点的输入、输出、返回x坐标、返回y坐标和返回z坐标。在主程序中定义该类的一个对象,做到能够输入坐标,输出坐标,并且输出到原点的距离。
#include <iostream>
#include<math.h>
using namespace std;
class Point{
private:
double x;
double y;
double z;
public:
Point(double xv=0,double yv=0,double zv=0);//有参构造
Point(const Point &p); //拷贝构造
~Point(); //析构函数
void show() const; //显示Point信息
double area()const; //面积=0
void setX(double xv); //设置X坐标
void setY(double yv); //设置Y坐标
void setZ(double zv); //设置Z坐标
double getX() const; //获取X坐标
double getY() const; //获取Y坐标
double getZ() const; //获取Z坐标
};
//有参构造
Point::Point(double xv,double yv,double zv){
x=xv;
y=yv;
z=zv;
cout<<"Point Constructor run"<<endl;
cout<<"主程序设置x,y,z的坐标分别是"<<x<<","<<y<<","<<z<<endl;
}
//拷贝构造
Point::Point(const Point &p){
x=p.x;
y=p.y;
z=p.z;
cout<<"Point CopyConstructor run"<<endl;
}
//析构函数
Point::~Point(){
cout<<"Point Destructor run"<<endl;
}
//显示Point
void Point::show() const{
cout<<"输出x,y,z坐标\n"<<endl;
cout<<"("<<x<<","<<y<<","<<z<<")";
}
//设置X坐标
void Point::setX(double xv){
x=xv;
}
//设置Y坐标
void Point::setY(double yv){
y=yv;
}
//设置Z坐标
void Point::setZ(double zv){
z=zv;
}
//面积函数
double Point::area() const{
return 0;
}
//获取X坐标
double Point::getX() const{
return x;
}
//获取Y坐标
double Point::getY() const{
return y;
}
//获取Z坐标
double Point::getZ() const{
return z;
}
int main(){
Point point1(2.0,3.0,4.0),point2(3.0,4.0,5.0);
point1.show();
point2.show();
double dis1,dis2;
dis1=sqrt(2.0*2.0+3.0*3.0+4.0*4.0);
dis2=sqrt(3.0*3.0+4.0*4.0+5.0*5.0);
cout<<"\npoint1距原点的距离"<<dis1<<endl;
cout<<"\npoint2距原点的距离"<<dis2<<endl;
return 0;
}