5、析构函数
作用:
对象销毁前,做清理工作。
具体的清理工作,一般和构造函数对应
比如:如果在构造函数中,使用了new分配了内存,就需要在析构函数中用delete释放。
如果构造函数中没有申请资源(主要是内存资源)
那么很少使用析构函数。
函数名:
~类型
没有返回值,没有参数,最多只能有一个析构函数
访问权限:
一般使用public
使用方法:
不能主动调用。
对象销毁时,自动调用*****(很重要)
如果不定义,编译器会自动生成一个析构函数(什么也不做)。
#include<iostream>
#include<Windows.h>
#include<string>
using namespace std;
#define ADDR_LEN 64
class Cat
{
public:
Cat();
Cat(const Cat &other);
string getName();
int getAge();
void setAddr(char*addr);
void description();
//运算符重载函数
Cat &operator=(const Cat &other);
//析构函数
~Cat();
private:
string name;
int age;
char*addr;
};
string Cat::getName()
{
return name;
}
int Cat::getAge()
{
return age;
}
void Cat::setAddr(char*addr)
{
if (!addr)
{
return;
}
strcpy_s(this->addr, ADDR_LEN, addr);
}
void Cat::description()
{
cout << "姓名:" << name << " 年龄: " << age << " 地址: " << addr << endl;
}
Cat::Cat()
{
cout << "调用构造函数" <<this<< endl;
name = "小狸花";
age = 14;
addr = new char[ADDR_LEN];
strcpy_s(addr, ADDR_LEN, "小狸花");
}
Cat::Cat(const Cat &other)
{
cout << "调用拷贝构造函数" << endl;
name = other.name;
age = other.age;
addr = new char[ADDR_LEN];
strcpy_s(addr, ADDR_LEN, other.addr);
}
Cat & Cat::operator=(const Cat &other)
{
//防止对象给自己赋值f1 =f1;
if (this ==&other)
{
return *this;
}
//比如执行:f1=f2
//就会调用:f1.operator=(f2);
name = other.name;
age = other.age;
//如果有必要,需要先释放自己的资源(动态内存)
delete addr;
addr = new char[ADDR_LEN];
//深拷贝
strcpy_s(addr, ADDR_LEN, other.addr);
//返回对象本身的引用,以便为了方便做链式处理;f1=f2=f3
return *this;
}
Cat::~Cat()
{
cout << "调用析构函数:"<<this << endl;
delete addr;
}
void test()
{
Cat h1;
{
Cat h2;
}
cout << "test()end." << endl;
}
int main()
{
test();
system("pause");
return 0;
}