关于构造 和析构函数
class u
{
public:
static int count;
u(){count++;}
~u(){count--;cout < < "~u " < <endl;}
};
int u::count = 0;
u f2(u u1){
u1.count++;
return u1;
}
u f3(u u3){cout < < "in f3(): " < <endl;return u3;}
void f4(u u2){}
void main()
{
u u1;
cout < < "u1: " < <u::count < <endl;
u u2;
cout < < "u2: " < <u::count < <endl;
u1 = f3(u2);
cout < < "after f3(): " < <endl;
cout < < "count: " < <u::count < <endl;
f4(u2);
cout < < "after f4(): " < <endl;
cout < < "count: " < <u::count < <endl;
}
运行结果:
u1:1
u2:2
in f3():
~u
~u
after f3():
count:0
~u
after f4():
count:-1
~u
~u
为什么在in f3()里 两次析够 在f4()里只有一次?
[解决办法]
f3的返回类型是u,返回的时候会构造一个u;f4的返回值是void,不需要。
你没有跟踪拷贝构造函数。
[解决办法]
f3( u );//这里传递参数一次
return u3; //返回又一次
f4( u );//这里一次
return; //不返回,所以没有
关于构造 和析构函数,该怎么解决
关于构造 和析构函数classu{public:staticintcountu(){count++}~u(){count--cout ~u endl}}
