Chinaunix
标题:
析构函数的调用
[打印本页]
作者:
hugoleong
时间:
2012-03-31 12:51
标题:
析构函数的调用
#include<iostream>
#include<string.h>
using namespace std;
class A
{
private:
char *string;
public:
A();
A( char* _string);
void print()
{
cout<<"####"<<string<<endl;
}
~A();
A operator=(A &other);
};
A A:
perator= (A &other)
{
int length;
if(this == &other)
return *this;
length = strlen(other.string);
free(string);
string = (char*)malloc(length + 1);
strcpy(string, other.string);
return *this;
}
A::~A()
{
cout<<"析构函数调用";
}
A::A()
{
string = (char*)malloc(1);
string[0]='\0';
}
A::A( char* _string)
{
int length;
length = strlen(_string);
string= (char*)malloc(length + 1);
strcpy(string, _string);
string[length] = '\0';
}
int main(void)
{
A a1;
A a2("how are you"
;
a1.print();
a2.print();
a1 = a2;
a1.print();
a2.print();
}
运行结果:
####
####how are you
析构函数调用####how are you
####how are you
析构函数调用析构函数调用
ps: 为什么在第一个a2.printf()后就调用一次。。。
作者:
x5miao
时间:
2012-03-31 13:49
A operator=(A &other);
返回值改成A&
作者:
hugoleong
时间:
2012-04-01 16:14
回复
2#
x5miao
嗯嗯,这样就可以了,请问为什么嘞??
作者:
x5miao
时间:
2012-04-01 19:30
本帖最后由 x5miao 于 2012-04-01 19:50 编辑
回复
3#
hugoleong
非引用的返回值是一个临时对象。函数退出,临时对象在释放之前自动调用了析构函数。
作者:
三月廿七
时间:
2012-04-01 23:54
本帖最后由 三月廿七 于 2012-04-02 00:12 编辑
我写 c++ 程序从来不释放,写什么析构函数纯粹浪费时间..
windows不像移动平台,内存少的都可怜,windows 有的是内存
要充分利用 pc 提供的优良环境,!
除非内存撑爆了,我才会去写析构函数
作者:
x5miao
时间:
2012-04-02 00:16
回复
5#
三月廿七
那是因为编译器自动给你生成了析构函数而已
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2