免费注册 查看新帖 |

Chinaunix

广告
  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1532 | 回复: 5
打印 上一主题 下一主题

析构函数的调用 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 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()后就调用一次。。。

论坛徽章:
0
2 [报告]
发表于 2012-03-31 13:49 |只看该作者
  A operator=(A &other);
返回值改成A&

论坛徽章:
0
3 [报告]
发表于 2012-04-01 16:14 |只看该作者
回复 2# x5miao


    嗯嗯,这样就可以了,请问为什么嘞??

论坛徽章:
0
4 [报告]
发表于 2012-04-01 19:30 |只看该作者
本帖最后由 x5miao 于 2012-04-01 19:50 编辑

回复 3# hugoleong


    非引用的返回值是一个临时对象。函数退出,临时对象在释放之前自动调用了析构函数。

论坛徽章:
0
5 [报告]
发表于 2012-04-01 23:54 |只看该作者
本帖最后由 三月廿七 于 2012-04-02 00:12 编辑

我写 c++ 程序从来不释放,写什么析构函数纯粹浪费时间..
windows不像移动平台,内存少的都可怜,windows 有的是内存

要充分利用 pc 提供的优良环境,!
除非内存撑爆了,我才会去写析构函数

论坛徽章:
0
6 [报告]
发表于 2012-04-02 00:16 |只看该作者
回复 5# 三月廿七


    那是因为编译器自动给你生成了析构函数而已
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP