很简单的拷贝构造函数次序小困惑
书上的代码:
#include <iostream>
#include <cmath>
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<<"Point拷贝构造函数被调用"<<X<<endl;//这里我刻意加的就是看它次序
}
//类的组合
class Line
{
public:
Line (Point xp1, Point xp2);
Line (Line &);
double GetLen(){return len;}
private:
Point p1,p2;
double len;
};
//组合类的构造函数
Line:: Line (Point xp1, Point xp2)
:p1(xp1),p2(xp2)
{
cout<<"Line构造函数被调用"<<endl;
double x=double(p1.GetX()-p2.GetX());
double y=double(p1.GetY()-p2.GetY());
len=sqrt(x*x+y*y);
}
void main()
{
Point myp1(3,9),myp2(6,8); //建立Point类的对象
Line line(myp1,myp2);
}
运行结果是:
Point拷贝构造函数被调用6
Point拷贝构造函数被调用3
Point拷贝构造函数被调用3
Point拷贝构造函数被调用6
Line构造函数被调用
解释:
主函数中Line line(myp1,myp2);此时执行次序如下:
调用组合类Line的构造函数,myp1传给Line构造函数第一个xp1,一次调用point构造函数,结果应该是:
Point拷贝构造函数被调用6,
第二次myp2传给构造函数第一个xp2,结果应该好似Point拷贝构造函数被调用6,
然后根据组合类内嵌对象构造函数调用次序应该是先构造p1,后构造p2,
结果应该是:
Point拷贝构造函数被调用3
Point拷贝构造函数被调用6
显然后面2个是正确的,
但是初始的2个拷贝构造函数为什么次序不对呢?
难道实参和形参结合的时候是从右到左,而不是正常的从左到右吗?