c++之析构函数

#include <iostream>

using namespace std;

class Pointer
{
public:
	Pointer();
	Pointer(int _x, int _y);
	Pointer(const Pointer &other);
	~Pointer();
	
	void show();
private:
	int *x;
	int *y;
};

Pointer::Pointer() : x(new int(-1)),
	y(new int(-1))
{
	cout << "Default Constructor" << endl;
}

Pointer::Pointer(int _x, int _y) : x(new int(_x)),
	y(new int(_y))
{
	cout << "Argument Constructor" << endl;
}

Pointer::Pointer(const Pointer &other) : x(new int(*(other.x))),
	y(new int(*(other.y)))
{
	cout << "Copy Constructor" << endl;
}

Pointer::~Pointer() //析构函数
{
	cout << "Destructor" << endl;
	if (x != NULL) {
		delete x;
		x = NULL;
	}

	if (y != NULL) {
		delete y;
		y = NULL;
	} 
}

void Pointer::show()
{
	cout << "X = " << *x << " Y = " << *y << endl;
}

int main(int argc, const char *argv[])
{
#if 0
	Pointer p;
	p.show();
	Pointer p1(10, 10);
	p1.show();
	Pointer p2(p1);
	p2.show();
	cout << "---------" << endl;
#endif
	Pointer *p3 = new Pointer;//
	delete p3;
	p3 = NULL;

	return 0;
}

析构函数的特点:

无参数,返回值,但有this指针

析构函数不能用const修饰

一个类只有一个析构函数,不能重载

如果不手动销毁对象指针,程序运行结束时,编译器不会进行处理,操作系统会直接进行内存回收,但是不会调用析构函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值