面向对象的编程之析构函数

5、析构函数
作用:
对象销毁前,做清理工作。
 具体的清理工作,一般和构造函数对应
比如:如果在构造函数中,使用了new分配了内存,就需要在析构函数中用delete释放。
如果构造函数中没有申请资源(主要是内存资源)
那么很少使用析构函数。
函数名:
~类型
没有返回值,没有参数,最多只能有一个析构函数
访问权限:
一般使用public
使用方法:
不能主动调用。
对象销毁时,自动调用*****(很重要)
如果不定义,编译器会自动生成一个析构函数(什么也不做)。19e8e35e71f24580a851b6c8246095ee.png

#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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值