第四章类与对象知识进阶练习题
题目:使用对象成员构成新类。
要求先定义一个Point类,用于产生水平面上的点对象。两点决定一条线段,即线段由点构成。因此,Line类使用Point类的对象作为数据成员,然后在Line类的构造函数中求出线段的长度。
#include<iostream>
#include<cmath>
using namespace std;
class Point
{
private:
double X,Y;
public:
Point(double a, double b);
Point(Point& p);
double GetX();
double GetY();
};
class Line
{
private:
Point A, B; //定义两个Point类对象成员
double Length;
public:
Line(Point p1, Point p2); //Line类的构造函数原型,函数体在类外实现
double GetLength();
};
Point::Point(double a, double b)
{
X = a;
Y = b;
}
Point::Point(Point& p)
{
X = p.X;
Y = p.Y;
}
double Point::GetX()
{
return X;
}
double Point::GetY()
{
return Y;
}
Line::Line(Point p1, Point p2):A(p1), B(p2)
{
Length = sqrt((p1.GetX() - p2.GetX()) * (p1.GetX() - p2.GetX())
+ (p1.GetY() - p2.GetY()) * (p1.GetY() - p2.GetY()));
}
double Line::GetLength()
{
return Length;
}
int main()
{
Point A(1, 2), B(3, 4);
Line line(A, B);
cout << line.GetLength() << endl;
return 0;
}