C++复制构造函数和构造函数调用小困惑

最近看清华大学郑莉老师的C++课程,过C++的基础知识。遇到了一点小问题。
B站清华大学C++课程
在进行类组合例子的调试中,有些不解的地方。先上代码。

#include "pch.h"
#include <iostream>
using namespace std;

class Point {
public:						//外部接口
	Point(int xx = 0, int yy = 0) {		//构造函数
		x = xx;
		y = yy;
	}
	Point(Point &p);		//复制构造函数
	int getX() {
		return x;
	}
	int getY() {
		return y;
	}
private:				//私有数据
	int x, y;
};

//成员函数的实现
Point::Point(Point &p) {
	x = p.x;
	y = p.y;
	cout << "Calling the copy constructor" << endl;
}

class Line{
public:
	Line(Point xp1, Point xp2);
	Line(Line &l);
	double getLen() { return len; }
private:
	Point p1, p2;
	double len;
};
Line::Line(Point xp1, Point xp2):p1(xp1),p2(xp2)
{
	//p1 = xp1;
	//p2 = xp2;
	cout << "Calling constructor of Line" << endl;
	double x = static_cast<double>(p1.getX() - p2.getX());
	double y = static_cast<double>(p1.getY() - p2.getY());
	len = sqrt(x*x + y * y);
}

Line::Line(Line &l):p1(l.p1), p2(l.p2) 
{
	//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);
	cout << "The lenth of the line is: " << line.getLen() << endl;
	cout << "The lenth of the line2 is: " << line2.getLen() << endl;
	return 0;
}

在这里插入图片描述
Point的复制构造函数共调用了6次。
而简单替换两个函数:

Line::Line(Point xp1, Point xp2)//:p1(xp1),p2(xp2)
{
	p1 = xp1;
	p2 = xp2;
	cout << "Calling constructor of Line" << endl;
	double x = static_cast<double>(p1.getX() - p2.getX());
	double y = static_cast<double>(p1.getY() - p2.getY());
	len = sqrt(x*x + y * y);
}

Line::Line(Line &l)//:p1(l.p1), p2(l.p2) 
{
	p1 = l.p1;
	p2 = l.p2;
	cout << "Calling the copy constructor of Line" << endl;
	len = l.len;
}

结果如下:
在这里插入图片描述
Point的复制构造函数共调用了2次。
非常不解。
p1 = xp1;与p1(xp1)不是一样的嘛?
先记录下来。


问题初步解决:

Line::Line(Point xp1, Point xp2)//:p1(xp1),p2(xp2)
{
	Point p1 = xp1;
	Point p2 = xp2;
	cout << "Calling constructor of Line" << endl;
	double x = static_cast<double>(p1.getX() - p2.getX());
	double y = static_cast<double>(p1.getY() - p2.getY());
	len = sqrt(x*x + y * y);
}

Line::Line(Line &l)//:p1(l.p1), p2(l.p2) 
{
	Point p1 = l.p1;
	Point p2 = l.p2;
	cout << "Calling the copy constructor of Line" << endl;
	len = l.len;
}

可实现六次调用复制构造函数
但,新问题出现:调试的时候发现Line::Line(Point xp1, Point xp2)首先调用了Point的构造函数,并初始了p1,p2为(0,0),这又是为什么呀?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值