(C++)关于复制构造函数的调用次数
以下是我的源代码:
#include<iostream>
#include<cmath>
using namespace std;
class Point
{
public:
Point(int xx=0,int yy=0)
{
x=xx;
y=yy;
cout<<"调用Point的构造函数"<<endl;
}
~Point(){cout<<"调用Point的析构函数"<<endl;}
Point(Point &p)
{
this->x=p.x;
this->y=p.y;
cout<<"调用Point的复制构造函数"<<endl;
}
int getX(){return x;}
int getY(){return y;}
private:
int x,y;
};
class Line
{
public:
Line(Point p1,Point p2):myp1(p1),myp2(p2)
{
cout<<"调用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(){cout<<"调用Line的析构函数"<<endl;}
Line(Line &l)
{
this->myp1=l.myp1;
this->myp2=l.myp2;
this->len=l.len;
cout<<"调用Line的复制构造函数"<<endl;
}
float getLen(){return len;}
private:
Point myp1,myp2;
double len;
};
void test01()
{
Point myp1(1,1),myp2(4,5);
Line line(myp1,myp2);
Line line2(line);
cout<<"The length of the line is:"<<line.getLen()<<endl;
cout<<"The length of the line2 is:"<<line2.getLen()<<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果为:
调用Point的构造函数
调用Point的构造函数
调用Point的复制构造函数
调用Point的复制构造函数
调用Point的复制构造函数
调用Point的复制构造函数
调用Line的构造函数
调用Point的析构函数
调用Point的析构函数
调用Point的构造函数
调用Point的构造函数
调用Line的复制构造函数
The length of the line is:5
The length of the line2 is:5
调用Line的析构函数
调用Point的析构函数
调用Point的析构函数
调用Line的析构函数
调用Point的析构函数
调用Point的析构函数
调用Point的析构函数
调用Point的析构函数
请按任意键继续. . .
求问为什么在Line构造函数之前会调用四次Point的复制构造函数??
Line line(myp1,myp2);
这里参数传入2次
Line(Point p1,Point p2):myp1(p1),myp2(p2)
这里赋值又是2次