前言:
如果定义一个类,有其默认的构造函数,则使用new动态实例化一个对象数组,不是件难事,如下代码:
1 #include <memory> 2 #include <iostream> 3 4 using namespace std; 5 6 class Animal 7 { 8 public: 9 #if 1 //用于后面演示,无默认构造函数 10 Animal() : num(0) 11 { 12 cout << "Animal constructor default" << endl; 13 } 14 #endif 15 Animal(int _num) : num(_num) 16 { 17 cout << "Animal constructor param" << endl; 18 } 19 20 ~Animal() 21 { 22 cout << "Animal destructor" << endl; 23 } 24 25 void show() 26 { 27 cout << this->num << endl; 28 } 29 30 private: 31 int num; 32 }; 33 34 int main() 35 { 36 Animal *ani = new Animal[5]; 37 38 delete[]ani; 39 40 system("pause"); 41 return 0; 42 }
运行结果: