C++之--析构函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zhang_1218/article/details/78252529

C++之--析构函数

析构函数也是一个·特殊的成员函数,其作用与构造函数刚好相反,析构函数是用进行清理工作的

析构函数的定义方式为在类名前加上“~”。而“~”在C++中是位取反运算符,所以从这里也可以想到,析构函数是与构造函数作用相反的成员函数。

下面来看一下代码:

class  Student
{
public:
	//全缺省构造参数
	Student(char* Name = "吴力", char* Sex = "男", int Age = 19)
	{
		this->name = Name;
		this->sex = Sex;
		this->age = Age;
	}
	//析构函数
	~Student()
	{
		cout << "析构函数的测试" << endl;
	}

	void showinfo()
	{
		cout << "name: " << name << endl;
		cout << "sex: " << sex << endl;
		cout << "age: " << age << endl;
	}
private:
	int age;
	char* name;
	char* sex;
	int* ptr;
};

再看下面的例子

class Array
{
    public :
    Array (int size)
    {
        str = (int *)malloc( size*sizeof (int));
    }
    // 这里的析构函数需要完成清理工作(释放动态开辟的内存)。
    ~ Array ()
    {
        if (str)
        {
            free(str );
_           str = 0;
        }
    }
private :
    int* str ;
};

总结来说:

    1、当对象的生命周期结束时,程序会自动调用析构函数来进行清理工作。

    2、析构函数体内并不是删除对象,而是做一些清理工作。

    3、同构造函数一样,C++在类内部也是默认提供了析构函数。

    4、一个类有且只有一个析构函数。若未显示定义,系统会自动生成缺省的析构函数。

    5、析构函数无参数无返回值。

猜你喜欢

转载自blog.csdn.net/Zhang_1218/article/details/78252529