亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

您好,請問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條經驗 獲得超4個贊

用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 關注
  • 299 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號