對於下面的代碼,爲什麼「A關閉:3」打印兩次?C++析構函數是如何執行的?
#include <stdio.h>
class A
{
public:
int a;
A(int n)
{
a = n;
printf("This is A: %d.\n", a);
}
A()
{
a = 0;
printf("This is A: %d.\n", a);
}
~A()
{
printf("A is closed: %d.\n", a);
}
};
class B
{
public:
A a;
B()
{
a = A(3);
}
};
void f()
{
B b;
}
int main()
{
f();
return 0;
}
輸出:
This is A: 0.
This is A: 3.
A is closed: 3.
A is closed: 3.
這是_got_是一個騙局:/但我找不到它 –