北大程序設計與算法(三)測驗題彙總(2020春季)
描述
程序填空,輸出指定結果
#include <iostream>
using namespace std;
class A {
public:
int i;
A(int x) { i = x; }
// 在此處補充你的代碼
};
int main()
{
A a(1);
A * pa = new A(2);
delete pa;
return 0;
}
輸入
無
輸出
2
1
樣例輸入
無
樣例輸出
2
1
來源
Guo Wei
分析
我們發現1和2的輸出順序是相反的,那麼很容易聯想到析構函數的調用與構造函數的調用順序相反。
#include <iostream>
using namespace std;
class A {
public:
int i;
A(int x) { i = x; }
~A(){ cout << i << endl;}
};
int main()
{
A a(1);
A * pa = new A(2);
delete pa;
return 0;
}
執行效果