#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修饰
一个类只有一个析构函数,不能重载
如果不手动销毁对象指针,程序运行结束时,编译器不会进行处理,操作系统会直接进行内存回收,但是不会调用析构函数