猿问

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

#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()

杨魅力
浏览 272回答 1
1回答

Helenr

用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;}&nbsp;
随时随地看视频慕课网APP
我要回答