大家好 我比较2 帮我看下这个简单的问题
这段代码是一个改错...
我知道错在哪...
因为MakeCat()函数要按引用返回指针指向的对象
因此在MakeCat()函数里不能delete掉它
进而有内存泄露的问题...
我的问题是:为什么一个非const的Boots可以调用一个const的GetAge()函数(可能这个说法有误)
Boots.GetAge()
谢谢
#include <iostream>
using namespace std;
class CAT
{
public:
CAT(int age)
{
itsAge = age;
}
~CAT()
{
//destructor
}
int GetAge() const
{
return itsAge;
}
private:
int itsAge;
};
CAT &MakeCat(int age);
int main()
{
int age = 7;
CAT Boots = MakeCat(age);
cout<<"Boots is "<<Boots.GetAge()<<" years old"<<endl;
char response;
cin>>response;
return 0;
}
CAT &MakeCat(int age)
{
CAT *pCat = new CAT(age);
return *pCat;
}
[解决办法]
非const的实例可以调用一个const方法.
反过来不行
[解决办法]
CAT Boots = MakeCat(age);//这儿copy构造生成新的Boots 对象,MakeCat(age);中new的对象,已获取不到他的地址了
[解决办法]