析构函数
作用:
对象销毁前,做清理工作。
具体的清理工作,一般和构造函数对应
比如:如果在构造函数中,使用new分配了内存,就需在析构函数中用delete释放。
如果构造函数中没有申请资源(主要是内存资源),
那么很少使用析构函数。
函数名:
~类型
没有返回值,没有参数,最多只能有一个析构函数
访问权限:
一般都使用public
使用方法:
不能主动调用。
对象销毁时,自动调用。
如果不定义,编译器会自动生成一个析构函数(什么也不做)
#include <iostream>
#include <string>
using namespace std;
#define ADDR_LEN 64
//定义“人类”
class Human {
public:
Human(); //构造函数,可以写在类里面(由内联函数的效果),也可以写在外面
Human(int age, int salary);
//标准的拷贝构造函数是一个引用类型,别名后面的参数other可以省略
Human(const Human &other);
//析构函数
~Human();
void eat(); //类里面的方法,又称为成员函数
void sleep();
void work();
void play();
void description() const;
void setAddr(const char* addr);
string getName() const; //加const之后就不能在里面修改里面的值
int getAge();
int getSalary() const;
private:
//类内初始值,C++11以上的版本才支持
//在创建C++对象的时候,一开始就设定一个初始值,仅适用于特殊场合
string name = "牛少侠";
int age = 23;
int salary = 10000;
char* addr;
};
void Human::eat() {
cout << "吃鸡屁股, 喝可乐!" << endl;
}
void Human::sleep() {
cout << "夜深了!上床睡觉!" << endl;
}
void Human::work() {
cout << "我在工作..." << endl;
}
void Human::play() {
cout << "玩奇幻角色扮演!" << endl;
}
string Human::getName() const { //加const之后就不能在里面修改里面的值
return name;
}
void Human::description() const{
cout << "name: " << name
<< " age: " << age
<< " salary: " << salary
<< " 地址:" << addr << endl;
cout << (int)addr << endl;
}
void Human::setAddr(const char* addr) {
if (!addr){
return;
}
strcpy_s(this->addr, ADDR_LEN, addr);
cout << (int)this->addr << endl;
}
int Human::getAge() {
return age;
}
int Human::getSalary() const{
return salary;
}
//没有设置类内初始值时,进行手动构造函数
Human::Human() {
cout << "调用了构造函数" << this << endl;
name = "无名";
age = 18;
salary = 30000;
addr = new char[ADDR_LEN];
strcpy_s(this->addr, ADDR_LEN, "China");
}
Human::Human(int age, int salary) {
cout << "执行调用了自定义的构造函数:Human(int age, int salary)!" << endl;
//指针this指向类的对象
this->age = age;
this->salary = salary;
this->name = "天杀的";
addr = new char[64];
strcpy_s(this->addr, ADDR_LEN, "China");
}
//拷贝构造函数
//相当于const Human& other = b1;
//一个类中只能定义一个拷贝构造函数,不能有其他重载形式
Human::Human(const Human& other) {
cout << "执行调用了拷贝构造函数:Human(const Human& other)!" << endl;
name = other.name;
age = other.age;
salary = other.salary;
addr = new char[ADDR_LEN];
strcpy_s(addr, ADDR_LEN, "China");
}
Human::~Human() {
cout << "调用析构函数" << this << endl;
delete[] addr;
}
void test(void) {
Human f1;
{
Human f2;
}
cout << "test()...end" << endl;
}
int main(void) {
test();
return 0;
}
输出为: