下列程序的运行结果是
#include <iostream.h>
class point
{ int x,y;
public:
point(int a,int b)
{x=a;y=b;
cout<<"calling the constructor function."<<endl;
}
point(point &p);
friend point move(point q);
~point(){cout<<"calling the destructor function.\n";}
int getx() {return x;}
int gety() {return y;}
};
point::point(point &p)
{x=p.x; y=p.y;
cout<<"calling the copy_initialization constructor function.\n";
}
point move(point q)
{cout<<"OK!\n";
int i,j;
i=q.x+10;
j=q.y+20;
point r(i,j);
return r;
}
void main()
{ point m(15,40),p(0,0);
point n(m);
p=move(n);
cout<<"p="<<p.getx()<<","<<p.gety()<<endl;
}
答案:
calling the constructor function.
calling the constructor function.
calling the copy_initialization constructor function.
calling the copy_initialization constructor function.
OK!
calling the constructor function.
calling the copy_initialization constructor function.
calling the destructor function.
calling the destructor function.
calling the destructor function.
P=25,60
calling the destructor function.
calling the destructor function.
calling the destructor function.
说明:
(1)构造函数执行三次,分别初始化主函数中的对象m,p和move函数中的对象r。
(2)拷贝构造函数共执行了三次。第一次,初始化对象n;第二次在调用函数move()时,实参n给形参q进行初始化;第三次是执行函数move的return r;语句时,系统用r初始化一个临时对象时使用了拷贝构造函数。
(3)析构函数执行了六次。在退出函数move时释放对象r和q共调用二次;返回主函数后,临时对象赋值给对象p后,释放临时对象又调用一次析构函数;最后退出整个程序时释放对象m,n和p调用三次。