为了账号安全,请及时绑定邮箱和手机立即绑定

您好,请问C++这段代码该如何释放堆内存?

您好,请问C++这段代码该如何释放堆内存?

C++ C
杨魅力 2021-10-07 11:07:51
#include "iostream"using namespace std;class simplecat{public:simplecat(int age,int weight){itsage=age; itsweight=weight;}~simplecat(){cout<<" destructor "<<endl;}int getage() const {return itsage;}int getweight() const {return itsweight;}private:int itsage;int itsweight;};simplecat & thefunction(){simplecat * p = new simplecat (5,9);cout<<p<<endl;return *p;}void main(){simplecat & rcat= thefunction();int age=rcat.getage();cout<<"rcat is "<<rcat.getage ()<<" years old"<<endl;} 书上对于释放的方法说了三种,可是我没看懂,帮是说下这三中方法是怎么做的。1、main函数里的第一行声明一个 simplecat 对象,然后从函数 thefunction()按值返回该对象2、仍是在 thefunction() 中声明一个自由存储区的simple,但是让函数thefunction()返回 一个指向该对象的指针。这样使用完该对象后,调用函数可将该指针删除3、在调用函数中声明对象,然后按引用将它传递给函数thefunction()
查看完整描述

1 回答

?
Helenr

TA贡献1780条经验 获得超3个赞

用delete就可以了 只要给出了分配内存的首地址就可以了释放代码如下 如果我的回答让你满意的话 请选为满意答案哦#include "iostream"
using namespace std;
class simplecat
{
public:
simplecat(int age,int weight){itsage=age; itsweight=weight;}
~simplecat(){cout<<" destructor "<<endl;}
int getage() const {return itsage;}
int getweight() const {return itsweight;}
private:
int itsage;
int itsweight;
};simplecat & thefunction()
{
simplecat * p = new simplecat (5,9);
cout<<p<<endl;
return *p;
}void main()
{
simplecat & rcat= thefunction();
int age=rcat.getage();cout<<"rcat is "<<rcat.getage ()<<" years old"<<endl;
delete &rcat;
}

 


查看完整回答
反对 回复 2021-10-10
  • 1 回答
  • 0 关注
  • 271 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信