C++中组合类的构造函数相关问题

主要目的:
本代码主要目的在于探究在组合类中创建以及初始化对象时,各个类的构造函数的调用情况。

/*------------------------------------------------------------------------
功能:探究组合类中构造函数的相关问题
运行结果:
Calling the argument constructor of point... // 对应92行创建点对象p1, p2
Calling the argument constructor of point...
Calling the copy constructor of Point... // 对应93行创建线段对象l1
Calling the copy constructor of Point...
Calling the copy constructor of Point...
Calling the copy constructor of Point...
Calling the argument constructor of Line...
Calling the default constructor of point... // 对应94行创建线段对象l2
Calling the default constructor of point...
Calling the copy constructor of Line...
The length of l1 is: 1.41421 // 对应95行
The length of l2 is: 1.41421 // 对应96行
--------------------------------------------------------------------------
Author: Zhang Kaizhou
Date: 2019-3-31 14:34:09
-------------------------------------------------------------------------*/
#include 
#include 

using namespace std;
//----------------------------------------------------------------
// 定义并实现一个点类Point
class Point{ // 点类
public:
    Point(); // 默认构造函数
    Point(int xx, int yy); // 含参构造函数
    Point(const Point& p); // 复制构造函数
    int getX();
    int getY();
private:
    int x, y;
};

Point::Point(){ // 默认构造函数的实现
    cout << "Calling the default constructor of point..." << endl;
}
Point::Point(int xx, int yy):x(xx), y(yy){ // 含参构造函数的实现
    cout << "Calling the argument constructor of point..." << endl;
}
Point::Point(const Point& p){ // 复制构造函数的实现
    x = p.x;
    y = p.y;
    cout << "Calling the copy constructor of Point..." << endl;
}

int Point::getX(){
    return x;
}

int Point::getY(){
    return y;
}

//-----------------------------------------------------------------------
// 定义并实现一个线段类Line,该类为组合类,其成员变量中包含有其他类的对象
class Line{ // 线类,是一个组合类,因为其成员变量中含有其他类的对象
public:
    Line(); // 默认构造函数声明
    Line(Point pp1, Point pp2); // 含参构造函数声明
    Line(const Line& l); // 复制构造函数声明
    double getLen();
private:
    Point p1, p2;
    double len;
};

Line::Line(){ // 默认构造函数的实现
    cout << "Calling the default constructor of Line..." << endl;
}
Line::Line(Point pp1, Point pp2):p1(pp1), p2(pp2){ // 含参构造函数的实现
    cout << "Calling the argument constructor of Line..." << endl;
    double x = static_cast (p1.getX() - p2.getX());
    double y = static_cast (p1.getY() - p2.getY());
    len = sqrt(x * x + y * y);
}
Line::Line(const Line& l){ // 复制构造函数实现
    p1 = l.p1;
    p2 = l.p2;
    len = l.len;
    cout << "Calling the copy constructor of Line..." << endl;
}

double Line::getLen(){
    return len;
}

//---------------------------------------------------------------
int main(){
    Point p1(0, 0), p2(1, 1); // 建立并初始化两个点对象p1, p2
    Line l1(p1, p2); // 建立并初始化一条线段对象l1
    Line l2(l1); // 调用复制构造函数,建立并初始化一条线段对象l2
    cout << "The length of l1 is: " << l1.getLen() << endl; // 输出线段l1的长度
    cout << "The length of l2 is: " << l2.getLen() << endl; // 输出线段l2的长度

    return 0;
}

你可能感兴趣的:(C++编程)