我在做練習,我不明白爲什麼下面的代碼返回:刪除C++行使
Program start, before f() -- number of objects: 0
After f(), before g() -- number of objects: 0
After g(), before h() -- number of objects: -1
After h(), program end -- number of objects: -1
沒有什麼錯F(),我明白了一切發生的事情。但是,我無法弄清楚在g()和h()中如何調用構造函數和析構函數。謝謝:)
代碼:
class Counted {
public:
Counted();
~Counted();
static int getNbrObj();
private:
static int nbrObj;
};
int Counted::nbrObj = 0;
Counted::Counted() {
nbrObj++;
}
Counted::~Counted() {
nbrObj--;
}
int Counted::getNbrObj() {
return nbrObj;
}
void f() {
Counted c;
Counted* pc = new Counted;
delete pc;
}
void g() {
Counted c1;
Counted c2 = c1;
}
void h() {
Counted c1;
Counted c2;
c2 = c1;
}
using namespace std;
void print_nbr_objects(const string& msg) {
cout << msg << " -- number of objects: "
<< Counted::getNbrObj() << endl;
}
int main() {
print_nbr_objects("Program start, before f()");
f();
print_nbr_objects("After f(), before g() ");
g();
print_nbr_objects("After g(), before h() ");
h();
print_nbr_objects("After h(), program end ");
}
我想這是功課。爲什麼不使用調試器? –