C++面试题
有以下代码:
1 A *pa = new A[10]; 2 delete pa;
则类 A 的构造函数和析构函数分别执行了( )次。
A.1,1 B.10,10 C.1,10 D.10,1
测试:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; class A { public: A() { cout << "构造函数" <<endl; } ~A() { cout << "析构函数 a=" << a <<endl; } void setA(int a) { this->a = a; } protected: private: int a; }; int main(void) { A *p = new A[10]; for (int i = 0; i< 10; ++i) { p[i].setA(i); } delete p; cout << "Hello World!" << endl; system("pause"); return 0; }
测试结果:
因为是delete p而不是delete []p所以只析构了P[0]。
Done is better than perfect.