请C++达人详细解释一下这个程序 太复杂了我看不明白

来源:百度知道 编辑:UC知道 时间:2024/05/29 06:25:03
#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<<"拷贝构造函数被调用"<<endl;
}
void fun1(Point p)
{
cout<<p.GetX()<<endl;
}
Point fun2()
{
Point A(1,2);
return A;
}
int main()
{
Point A(4,5);
Point B(A);
cout<<B.GetX()<<endl;
fun1(B);
B=fun2();
cout<<B.GetX()<<endl;
}

int main()
{
Point A(4,5);
Point B(A);//用已有对象A构造B,拷贝被调用
cout<<B.GetX()<<endl;
fun1(B);//当B直接作为参数传给函数时(引用的情况就不会),函数将建立B的临时拷贝,拷贝被调用
B=fun2();//fun2函数中的A是局部对象被返回给函数调者B时,会建立它的局部对象的一个临时拷贝去构造B,拷贝被调用
cout<<B.GetX()<<endl;
getchar();
}

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<<"拷贝构造函数被调用"<<endl;
}
void fun1(Point p)
{
cout<<p.GetX()<<endl;
}
Point fun2()
{
Point A(1,2);/*定义一个point类A,这个时候就调用第一个构造函数你看他的参数*/
return A;
}
int main()
{
Point A(4,5);/*同上面的一样*/
Point B(A);/*这个参数是个point类所以它调用的是第二个构造函数*/
cout<<B.GetX()<<endl;
fun1(B);
B=fun2();