C++按值返回对象和按引用返回对象问题
我在书上学习时有以下一个程序:
#include <iostream>
using namespace std;
class SimpleCat
{
public:
SimpleCat (int age, int weight);
~SimpleCat();
int GetAge(){return itsAge;}
int GetWeight(){return itsWeight;}
private:
int itsAge;
int itsWeight;
};
SimpleCat::SimpleCat(int age,int weight)
{
itsAge=age;
itsWeight=weight;
}
SimpleCat::~SimpleCat()
{
}
SimpleCat & TheFuction();
int main()
{
SimpleCat &rCat=TheFuction();
int age=rCat.GetAge();
cout<<"rCat is: "<<age<<" years old!"<<endl;
cout<<"&rCat: "<<&rCat<<endl;
SimpleCat *pCat=&rCat;
delete pCat;//删除指针后&rCat指向为空!
return 0;
}
SimpleCat &TheFuction()
{
SimpleCat *Frisky=new SimpleCat(5,9);
return *Frisky;
}
书上说这个程序有问题,问题我在注释中写出来了,书上说这个问题有三种解决办法:
1。在main()函数中声明一个SimpleCat对象,然后从函数TheFuction()按值返回该对象
2。仍在函数TheFuction()中声明一个位于自由存储区中的SimpleCat对象,但让函数TheFuction()返回一个指向该对象的指针,使用完该对象后,调用函数可以将该指针删除
3。在调用函数中声明对象,然后按引用将它传递给函数TheFuction()
我是一个初学者,不知道这三种解决方法怎么样去实现,希望大家指点一下我,最好把这三种方法对应的程序都写出来,让我更好的能学习什么是按值返回对象,什么是按引用返回对象,谢谢各位了,请各位不吝赐教
我分数太少了,只给20分,多谢
[解决办法]
第一个很好实现啊。
- C/C++ code
SimpleCat TheFuction(); int main() { SimpleCat rCat = TheFuction(); int age = rCat.GetAge(); cout << "rCat is: " << age << " years old!" << endl; cout << "&rCat: " << &rCat << endl; return 0; } SimpleCat TheFuction() { SimpleCat Frisky(5, 9); return Frisky; }
[解决办法]
第二个
- C/C++ code
SimpleCat* TheFuction(); int main() { SimpleCat* rCat = TheFuction(); int age = rCat->GetAge(); cout << "rCat is: " << age << " years old!" << endl; cout << "&rCat: " << &rCat << endl; delete rCat; return 0; } SimpleCat* TheFuction() { SimpleCat* Frisky = new SimpleCat(5, 9); return Frisky;}