Chinaunix
标题:
菜鸟求解
[打印本页]
作者:
qwerboo
时间:
2011-06-14 14:00
标题:
菜鸟求解
#include<iostream>
#include <stdio.h>
class Sequence{
public:
Sequence(int count=10,string name = "abc");
void show();
~Sequence();
int* _content;
int _count;
string _name;
};
Sequence::Sequence(int count,string name){
_count = count;
_content=new int[count];
_name = name;
for(int i=0;i<count;i++){
_content[i]=i;
}
this->show();
cout<<"constructor over!!"<<endl;
}
Sequence::~Sequence(){
cout << "execute ---"<<_name;
delete [] _content;
}
void Sequence::show(){
cout<<endl<<"{";
for(int i=0;i<_count;i++){
cout<<_content[i]<<" ";
}
cout<<"name = "<<_name<<endl;
cout<<"}"<<endl;
}
int main(){
Sequence s1;//这里有疑问,运行结果并没有调用析构函数,为啥啊?
//s1.~Sequence();
//s1.show();
//s1.~Sequence();
//s1.show();
//s1 = Sequence(3,"s1");
//s1.show();
//Sequence(5,"hello");
system("pause");
}
复制代码
作者:
int-main
时间:
2011-06-14 14:16
....
void test()
{
Sequence s1;
}
int main(){
test();
system("pause");
}
...
作者:
qwerboo
时间:
2011-06-14 14:19
哇 果然正确了 但是为啥啊? 能讲下嘛,或者推荐一本书看看,谢谢了!
作者:
int-main
时间:
2011-06-14 14:24
C++对象模型
作者:
tubocurarine
时间:
2011-06-15 09:25
你把 system("pause") 去掉试试?就应该行了。
pause 的时候, object 还没有被销毁,导致对象没有析构。
而 2L 的方法中, 对象的生成和销毁在另外一个函数中执行,所以构造函数和析构函数都得以执行。
关键在于,保证对象可以正常销毁。
作者:
chary8088
时间:
2011-06-15 09:42
Sequence s1 in the main function is local variable, whose lifetime will over when the main runs to end, so the deconstruct function will be called when main runs to the end.
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2