构造函数和拷贝构造函数的调用

#include <iostream>
#include <cmath>
using namespace std;
class Point {	//Point类定义
public:
    Point(int xx = 0, int yy = 0) {
        x = xx;
        y = yy;
    cout << "Calling constructor of Point" << endl;}
    Point(Point &p) {
    x = p.x;
    y = p.y;
    cout << "Calling the copy constructor of Point" << endl;}
int getX() { return x; }
    int getY() { return y; }

private:
    int x, y;
};
class Line {
public:
    Line(Point xp1, Point xp2);
    Line(Line &Ll);
    double getLen() { return len; }
private:
    Point p1, p2;
    double len;
};
Line::Line(Point xp1, Point xp2) : p1(xp1), p2(xp2) {//传参会拷贝构造,赋值也会拷贝构造
    cout << "Calling constructor of Line" << endl;
    double x =(p1.getX() - p2.getX());
    double y = (p1.getY() - p2.getY());
    len = sqrt(x * x + y * y);
}
Line::Line (Line &l): p1(l.p1), p2(l.p2) {
    cout << "Calling the copy constructor of Line" << endl;
    len = l.len;
}
int main() {
    Point myp1(1, 1), myp2(4, 5);
    Line line(myp1, myp2);
    Line line2(line);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/klftespace/article/details/80890620