#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;
}
- 1 回答
- 0 關注
- 299 瀏覽
添加回答
舉報
0/150
提交
取消