zoukankan      html  css  js  c++  java
  • C++析构函数

    本文地址:http://www.cnblogs.com/archimedes/p/cpp-destructor.html,转载请注明源地址

    功能:销毁对象前执行清除工作

    格式:

    [类名::]~类名()

    {

       ....

    }

    class Student
    {public:
        Student(...);
        ~Student();//~符号
        void display()const;
    private:
        int    m_iNum;
        string m_strName;
        char   m_cSex;  
    };
    Student::~Student()
    { cout<<"Destructor "<<endl;}
    … …

    注意:

    函数名与类名相同,且函数名前加~

    没有参数、不能被重载

    不指定返回值

    常定义为public

    对象生命期结束时自动调用

    思考:

    通常不需人为定义析构函数,什么时候必须定义析构函数?

    一般,当类中含有指针成员,并且在构造函数中用指针指向了一块堆中的内存,则必须定义析构函数释放该指针申请的动态空间

    #include<iostream>
    using namespace std;
    
    class String
    {
    public:
        String();
        void display() const;
    private:
        char *m_pstr;
    };
    
    String::String()
    {
        m_pstr = new char[1000];
        strcpy(m_pstr, "hello");
    }
    void String::display() const
    {
        cout<<m_pstr<<endl;
    }
    /*
    String::~String()
    {
        //系统生成的
    }
    */
    int main()
    {
        String str;
        str.display();
        system("pause");
        return 0;
    } 

    看下面的代码,使用自己定义的析构函数--示例代码1:

    #include<iostream>
    using namespace std;
    
    class String
    {
    public:
        String();
        ~String();
        void display() const;
    private:
        char *m_pstr;
    };
    
    String::String()
    {
        m_pstr = new char[1000];
        strcpy(m_pstr, "hello");
    }
    String::~String()
    {
        delete []m_pstr;
    }
    void String::display() const
    {
        cout<<m_pstr<<endl;
    }
    
    int main()
    {
        String str;
        str.display();
        system("pause");
        return 0;
    } 

    示例代码2:

    #include<iostream>
    using namespace std;
    
    class String
    {
    public:
        String(char *ap = "china");
        ~String();
        void display() const;
    private:
        char *m_pstr;
    };
    
    String::String(char *ap)
    {
        m_pstr = new char[strlen(ap)+1];
        strcpy(m_pstr, ap);
    }
    String::~String()
    {
        delete []m_pstr;
    }
    void String::display() const
    {
        cout<<m_pstr<<endl;
    }
    
    int main()
    {
        String str1("USA");
        str1.display();
        String str2;
        str2.display();
        system("pause");
        return 0;
    } 

    如果要定义析构函数,通常也需要定义拷贝构造函数和赋值运算符的重载函数。关于拷贝构造函数,可以参考《C++拷贝构造函数

  • 相关阅读:
    前端模板Nunjucks简介
    git提交时支持文件名大小写的修改
    多行文本加省略号的处理方法
    前端性能优化实践方案总结
    使用gulp工具生成svgsprites
    koa简介
    JSX语法简介
    踩坑所引发出的appendChild方法的介绍
    React业务实践
    javascript--数组
  • 原文地址:https://www.cnblogs.com/wuyudong/p/cpp-destructor.html
Copyright © 2011-2022 走看看