#include <iostream>
using namespace std;
class Test
{
public:
int *p;
Test(int value)
{
p = new int(value);
}
~Test()
{
cout<<"值传递时delete p "<<endl;
delete p;
}
void PrintValue()
{
cout<<"The value is: "<<*p<<endl;
}
};
Test Func(const Test& t)//const + 引用
{
Test t2 = t;
t2.PrintValue();
cout<<"In the Func"<<endl;
return t2;
}
int main()
{
Test t1 = 33;
t1.PrintValue();
Test t3 = Func(t1);
t3.PrintValue();
cout<<endl;
}
上一章中结束对象值传递的一些问题,对其进行解决的方法是进行引用传递,这样就不用调用拷贝构造函数,同时加上const修饰符,确保调用的对象不被修改。
该代码打印结果如下:
The value is:33
The value is:33
In the Func
The value is:33
值传递时delete p
值传递时delete p
只调用了两次析构函数