最近看清华大学郑莉老师的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),这又是为什么呀?