C++一个析构函数的疑惑?
源代码如下:#include <iostream>
using namespace std;
class Demo {
int id;
public:
Demo(int i)
{
id = i;
cout << "id = " << id << " Constructed" << endl;
}
~Demo()
{
cout << "id = " << id << " Destructed" << endl;
}
};
Demo d1(1);
void Func() {
static Demo d2(2);
Demo d3(3);
cout << "Func" << endl;
}
int main() {
Demo d4(4);
d4 = 6;
cout << "main" << endl;
{ Demo d5(5); }
Func();
cout << "main ends" << endl;
return 0;
}
输出如下:
id=1 Constructed
id=4 Constructed
id=6 Constructed
id=6 Destructed
main
id=5 Constructed
id=5 Destructed
id=2 Constructed
id=3 Constructed
Func
id=3 Destructed
main ends
id=6 Destructed
id=2 Destructed
id=1 Destructed
我不明白为什么出现了三次 id=6,请各位指导一下。