拷贝构造函数的一点有关问题
拷贝构造函数的一点问题
为什么这个是调用了4次拷贝构造函数,是哪四次啊?
------解决方案--------------------
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2)
Line line1(m1,m2); m1,m2作为参数传入时发生两次拷贝构造,p1(xp1),p2(xp2)形参xp1,xp2分别调用拷贝构造初始化p1,p2; 所以共计4次;
拷贝构造发生情况:
1.作为函数参数传入
2.作为函数返回值传出
3.对象初始化时; X x; X xx = x;// 发生copy constuct
#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;
}
public:
int x;
int y;
};
Point::Point(Point &p){
x=p.x;
y=p.y;
cout<<"Point的拷贝构造函数!"<<endl;
}
class Line{
public:
Line(Point xp1,Point xp2);
Line(Line &l);
double getLen(){
return len;
}
public:
Point p1,p2;
double len;
};
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){
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::Line(Line &l):p1(l.p1),p2(l.p2){
cout<<"Line的拷贝构造函数!"<<endl;
len = l.len;
}
int main()
{
Point m1(1,1),m2(2,2);
//Point m3(m1);
Line line1(m1,m2);
cout<<endl<<endl;
//Line line2 = line1;
return 0;
}
为什么这个是调用了4次拷贝构造函数,是哪四次啊?
------解决方案--------------------
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2)
Line line1(m1,m2); m1,m2作为参数传入时发生两次拷贝构造,p1(xp1),p2(xp2)形参xp1,xp2分别调用拷贝构造初始化p1,p2; 所以共计4次;
拷贝构造发生情况:
1.作为函数参数传入
2.作为函数返回值传出
3.对象初始化时; X x; X xx = x;// 发生copy constuct