c++析构函数

【1】析构函数的作用

  析构函数的作用并不是删除对象,而是在撤销对象
  占用的内存之前完成一些清理工作,使这部分内存
  可以被程序分配给新对象使用。程序设计者事先设
  计好析构函数,以完成所需的功能,只要对象的生
  命期结束,程序就自动执行析构函数来完成这些工
  作。
  析构函数不返回任何值,没有函数类型,也没有函
  数参数。因此它不能被重载。一个类可以有多个构
  造函数,但只能有一个析构函数。

【2】

  一般情况下,类的设计者应当在声明类的同时定义
  析构函数,以指定如何完成“清理”的工作。如果用
  户没有定义析构函数,C++编译系统会自动生成一
  个析构函数,但它只是徒有析构函数的名称和形
  式,实际上什么操作都不进行。想让析构函数完成
  任何工作,都必须在定义的析构函数中指定。

#include<string>
#include<iostream>
using namespace std;

class Student
{
        public:
                Student(int n,string nam,char s)//构造函数
                {
                        num = n;
                        name = nam;
                        sex = s;
                        cout<<"Constructor called."<<endl;
                }
                ~Student()//析构函数
                {
                        cout<<"Destructor called."<<endl;
                }
        void display()
        {
                cout<<"num:"<<num<<endl;
                cout<<"name:"<<name<<endl;
                cout<<"sex:"<<sex<<endl<<endl;
        }

        private:
                int num;
                string name;
                char sex;
};


int main()
{
        Student stud1(10010,"wang_li",'f');
        stud1.display();
        Student stud2(10011,"zhang_fun",'m');
        stud2.display();
        return 0;
}
View Code
原文地址:https://www.cnblogs.com/fengdashen/p/3889281.html