构造函数析构函数问题
class Integer
{
public:
Integer(int _n){
cout<<"construction"<<endl;
n = _n;
};
Integer(Integer & copy){
cout<<"copy construction"<<endl;
n = copy.n;
};
operator=(Integer&Int){
cout<<"operator="<<endl;
n = Int.n;
};
~Integer(){
cout<<"deconstruction"<<endl;
};
private:
int n;
};
Integer returninteger(){
Integer Int(2);
return Int; //调试到此时怎么会调用Integer(Integer & copy)
}
void main()
{
Integer Int(0);
Int = returninteger();
}
运行结果为
construction
construction
copy construction
deconstruction
operator=
deconstruction
deconstruction
问题点数:20、回复次数:5Top
1 楼du51(郁郁思扬)回复于 2006-02-10 21:05:57 得分 5
Integer returninteger(){
Integer Int(2);//㈠
return Int;
}
void main()
{
Integer Int(0);//此处调用构造,输出construction
Int = returninteger();
/*此处先说等号右边。 在函数returninteger()中。先执行㈠输出construction
然后执行operator=函数.此函数有参数Integer & copy 刚才returninteger返回结果传入。产生临时对象,此时输出copy construction . 进入函数体后,临时对象销毁,输出deconstruction然后,输出operator=然后此运算(函数)结束。*/
/*在退出主程序前,销毁两对象.输出两个,deconstruction*/
}
Top
2 楼j10mqch(黑羽)回复于 2006-02-10 21:34:07 得分 5
我觉得应该是这样:
construction //主函数Int(0)构造
construction //函数returninteger中Int(2)构造
copy construction //由于Int(2)将要析构所以调用拷贝构造函数构造临时对象
deconstruction //Int(2)析构
operator= //调用operator=
deconstruction //临时对象析构
deconstruction //Int(0)析构
若主函数改成如下,则可以看到最后的两个deconstruction被!!!隔开.
void main()
{
Integer Int(0);
Int = returninteger();
cout<<"!!!"<<endl;
}Top
3 楼iawenll(菜鸟一个)回复于 2006-02-10 22:29:32 得分 5
关键点还是在临时对象的产生!
由于Integer Int(2)是局部变量,所以在函数调用结束时,其自然消亡,
而为了能将其值返回,编译器自动生成一个临时变量!copy constructor就是这时调用的,
上面的已经说明。
建议楼主查找一下资料,看看有关临时对象的问题,明白其中的原理,一切也就明白了。^&^Top
4 楼armman()回复于 2006-02-10 22:47:42 得分 3
在函数返回一个对象时,要使用返回值初始化调用函数内部的一个(隐藏)对象,这时也要调用复制初始化函数,在该隐藏对象的生命周期结束,同样也要调用它的析构函数Top
5 楼beyondtkl(大龙驹<*好久没来了,兄弟们好吧。*>)回复于 2006-02-11 00:37:34 得分 2
inside c++ object
or others cpp books.Top




