| |||
| #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<<Y<<endl; } class Line { public: Line(Point xp1,Point xp2); Line(Line &L); double GtLen() {return len;} private: Point p1,p2; double len; }; Line::Line(Point xp1,Point xp2) 1(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); } Line::Line(Line &L) 1(L.p1),p2(L.p2){ cout<<"Line 拷贝构造"<<endl; len=L.len; } int main() { Point myp1(1,1),myp2(4,5); Line line(myp1,myp2); Line line2(line); cout<<"length of the line is:"; cout<<line.GtLen()<<endl; cout<<"length of the line2 is:"; cout<<line2.GtLen()<<endl; return 0; } 代码如上,运行显示: point 拷贝构造45 point 拷贝构造11 point 拷贝构造11 point 拷贝构造45 Line 构造 point 拷贝构造11 point 拷贝构造45 Line 拷贝构造 length of the line is:5 length of the line2 is:5 Press any key to continue 我的疑问是 1 为什么point的拷贝构造函数会先 执行myp2然后是myp1 2 为什么有四个拷贝构造函数呢? 我debug了一下,发现在执行 Line line(myp1,myp2);的时候 会先拷贝构造myp2(4,5),然后拷贝构造myp1(1,1),然后构造line,并拷贝构造myp1和myp2. 我主要是前两个点的拷贝构造不理解 谢谢大家的帮助啊 |