C++类的设计
设计一个Point类,设计一个Line类,要求Line类包含Point类对象,并提供获取线段长度的方法
- Point类的设计
class Point
{
private:
//为了保持封装性,坐标设置为私有属性
int coodr_x;
int coodr_y;
public:
Point();
~Point();
public:
//在公有属性提供可供类外访问的方法,这是类设计的一个原则
const int get_coodr_x(){ return this->coodr_x;};
const int get_coodr_y(){ return this->coodr_y;};
void set_coodr(int x,int y);
};
Point::Point()
{
}
Point::~Point()
{
}
void Point::set_coodr(int x,int y)
{
this->coodr_x = x;
this->coodr_y = y;
}
- Line类设计,设计的比较简单,主要展示类设计的封装性
class Line
{
private:
public:
//传参表初始化Point对象
Line(int x_1,int y_1,int x_2,int y_2);
~Line();
public:
Point p_1,p_2;
const float get_line();
};
Line::Line(int x_1,int y_1,int x_2,int y_2)
{
this->p_1.set_coodr(x_1,y_1);
this->p_2.set_coodr(x_2,y_2);
}
Line::~Line()
{
}
//获取线段长度方法
const float Line::get_line()
{
float line_a = abs((abs(this->p_1.get_coodr_x()))-(abs(this->p_2.get_coodr_x())));
float line_b = abs((abs(this->p_1.get_coodr_y()))-(abs(this->p_2.get_coodr_y())));
return abs(sqrt(line_a*line_a+line_b*line_b));
}
最后在main函数调用一下就能获得测试结果
int main()
{
Line l(0,0,4,4);
cout << l.get_line();
return 0;
}
执行结果