C++析构函数

简介:

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

格式:

[类名::]~类名()

{

   ....

}

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;
} 

如果要定义析构函数,通常也需要定义拷贝构造函数和赋值运算符的重载函数。

目录
相关文章
|
4月前
|
C++
C++析构函数定义为virtual虚函数,有什么作用?
C++析构函数定义为virtual虚函数,有什么作用?
31 0
|
3天前
|
编译器 C++
【C++从练气到飞升】03---构造函数和析构函数
【C++从练气到飞升】03---构造函数和析构函数
|
5天前
|
存储 编译器 对象存储
【C++】类与对象(构造函数、析构函数、拷贝构造函数、常引用)
【C++】类与对象(构造函数、析构函数、拷贝构造函数、常引用)
7 0
|
12天前
|
编译器 C++
【C++类和对象】构造函数与析构函数
【C++类和对象】构造函数与析构函数
【C++类和对象】构造函数与析构函数
|
25天前
|
编译器 C++
【C++成长记】C++入门 | 类和对象(中) |类的6个默认成员函数、构造函数、析构函数
【C++成长记】C++入门 | 类和对象(中) |类的6个默认成员函数、构造函数、析构函数
|
2月前
|
编译器 C语言 C++
【c++】类和对象(三)构造函数和析构函数
朋友们大家好,本篇文章我们带来类和对象重要的部分,构造函数和析构函数
|
2月前
|
开发框架 安全 编译器
【C/C++ 深入探讨构函数】C++ 编译器在什么情况下无法生成默认的析构函数?
【C/C++ 深入探讨构函数】C++ 编译器在什么情况下无法生成默认的析构函数?
52 1
|
2月前
|
设计模式 算法 编译器
【C++ 析构函数】C++ 私有析构函数的作用
【C++ 析构函数】C++ 私有析构函数的作用
32 1
|
2月前
|
Java 程序员 编译器
【C/C++析构函数 】C++中的“垃圾回收”机制_析构
【C/C++析构函数 】C++中的“垃圾回收”机制_析构
32 0
|
2月前
|
编译器 C++
『C++成长记』构造函数和析构函数
『C++成长记』构造函数和析构函数