注:以下内容为本人写代码测试所得出的结论,并没有参考太多资料,
暂时也不知道构造函数深入的原理,纯属个人笔记。
先定义两个类,一个是坐标点类Point,另一个是线段类Line:
class Point
{
public:
Point(int x=0, int y=0);
Point(const Point &p);
protected:
int x;
int y;
};
class Line
{
public:
Line(Point a, Point b);
Line(Point a, Point b, int x);
Line(int x1, int y1, int x2, int y2);
protected:
Point A;
Point B;
};
可见,Line类包含两个Point的对象。
先看看Point的成员函数的实现:
Point::Point(int x, int y)
{
this->x=x;
this->y=y;
cout<<"Point construct: "<<this->x<<", "<<this->y<<endl;
}
Point::Point(const Point &p) //拷贝构造函数。注意:初始化要程序员自己实现;系统自定义的拷贝构造函数会自动对新的对象进行初始化。
{
x=p.x;
y=p.y;
co