#include <iostream>
using namespace std;
class CA
{
int* a;
public:
friend class CB;
CA(int x)
{
cout<<"构造方式1被调用"<<endl;
a=new int[5];
*a=x;
}
CA()
{
cout<<"构造方式2被调用"<<endl;
a=new int[5];
*a=0;
}
~CA()
{
cout<<"析构被调用"<<endl;
*a=*a-1;
}
int get_a()
{
return *a;
}
};
class CB
{
public:
int get(CA test)
{
return *(test.a);
}
};
int main(int argc,char* argv[])
{
CA test(2);
CB test2;
cout<<test.get_a()<<endl;
cout<<test2.get(test)<<endl;
cout<<test2.get(test)<<endl;
getchar();
return 0;
}
输出结果是:
2
析构被调用
2
析构被调用
1
析构被调用
不知道你是否会奇怪,析构被调用之后为什么输出还是2
不是应该减1之后输出1吗
是的,其实减1操作已经完成了
只是类中的函数的返回值还是2,因为在返回之后才析构,减1
所以有一个顺序的问题,其实值已经变为1了。