#include <iostream> using namespace std; class A { public: int age; static int count; public: A(int i=2) : age(i) { this->age = i; cout << "gou zao "<<A::count << " age="<<age <<endl; A::count++; } ~A() { cout << "xi gou "<< endl; } }; int A::count = 0; int main(int argc, const char *argv[]) { A* arr = new A[10]; //产生10个A类对象 delete []arr; A *p = new A(25); delete p; A *p2 = new A; delete p2; return 0; }
gou zao 0 age=2 gou zao 1 age=2 gou zao 2 age=2 gou zao 3 age=2 gou zao 4 age=2 gou zao 5 age=2 gou zao 6 age=2 gou zao 7 age=2 gou zao 8 age=2 gou zao 9 age=2 xi gou xi gou xi gou xi gou xi gou xi gou xi gou xi gou xi gou xi gou gou zao 10 age=25 xi gou gou zao 11 age=2 xi gou
question
A *pa=new pa[10];
delete pa;
构造函数和析构函数分别执行了几次
answer:
#include <iostream>
using namespace std; class A { public: int age; static int count; public: A(int i=2) : age(i) { this->age = i; cout << "gou zao "<<A::count << " age="<<age <<endl; A::count++; } ~A() { cout << "xi gou "<< endl; } }; int A::count = 0; int main(int argc, const char *argv[]) { A* arr = new A[10]; //产生10个A类对象 delete arr; A *p = new A(25); //有参构造 delete p; A *p2 = new A;//default constructor delete p2; return 0; }
執行期間發生錯誤(RE) time: 0 memory: 3432 signal:6
gou zao 0 age=2 gou zao 1 age=2 gou zao 2 age=2 gou zao 3 age=2 gou zao 4 age=2 gou zao 5 age=2 gou zao 6 age=2 gou zao 7 age=2 gou zao 8 age=2 gou zao 9 age=2 xi gou
10次和1次