组合类的概念:一个类的成员是另一个类的对象,如下练习中Line类的成员a,b是Point类的对象。Point在类Line中创建对象a,b过程中,会调用构造函数对其进行初始化,而像类Line中Point对象的创建不含参数方式,也就需要Point类中含有不含参数的构造函数!
#include<iostream>
using namespace std;
class Point
{
public:
Point() {}; //不加这个会使得类Line中的声明变量不合法
Point(float a,float b);
void Display(void);
float Distance(Point &point);
float get_x() { return point_x; }
float get_y() { return point_y; }
private:
float point_x, point_y;
float distance;
};
Point::Point(float a, float b)
{
point_x = a;
point_y = b;
}
float Point::Distance(Point &point)
{
float distance;
distance = sqrt(pow(point_x - point.point_x,2) + pow(point_y - point.point_y,2));
return distance;
}
void Point::Display(void)
{
cout << "两点之间的距离:" << distance << endl;
}
class Line
{
public:
Line(Line &line); //拷贝构造函数实现
Line(Point &point1, Point &point2);
double Display(Line &line);
private:
Point a, b;
double distance;
};
Line::Line(Line &line)
{
a = line.a;
b = line.b;
}
Line::Line(Point &point1, Point &point2)
{
a = point1;
b = point2;
}
double Line::Display(Line &line)
{
distance = sqrt(pow(line.a.get_x() - line.b.get_x(), 2) + pow(line.a.get_y() - line.b.get_y(), 2));
return distance;
}
void main()
{
Point a;
Point b(10.2, 9.7), c(12.9, 15.6);
a = c;
cout << "两点之间的距离:" << a.Distance(b) << endl;
Line s(a, b);
Line s1(s);
cout << s1.Display(s1) << endl;
}
本人菜鸟刚学c++,凡有不对的地方还请大神指正,谢谢~