析构函数:假设我们创建了一个对象,当对象要结束时,要调用一个函数,这个函数就是析构函数
先来看看析构函数的原型是这样 ~Fruit();
class Fruit{
private:
int weight;
int price;
public:
~Fruit();//析构函数的原型
};
作用:在释放空间等(刚开始学习可能用不到)
特点:析构函数前面有一个~,函数没有参数,所以()里面没有任何东西
析构函数和类的写法:
class Fruit{
private:
int weight;
int price;
public:
~Fruit();//析构函数的原型
};
Fruit::~Fruit(){//析构函数的声名
cout<<"the process have end"<<endl;
}
完整代码:
#include<iostream>
using namespace std;
class Fruit{
private:
int weight;
int price;
public:
~Fruit();//析构函数的原型
};
Fruit::~Fruit(){//析构函数的声名
cout<<"the process have end"<<endl;
}
int main(){
Fruit apple;
return 0;
}
注意:
1.析构函数没有返回类型
2.析构函数默认的是不做任何行为,也就是说上面的代码中~Fruit()函数的{ }里面啥也没有
3.它的作用以后会用到,现在先了解了解