定义数组对象以后,对数组中的对象初始化的方式分为两种:
一种方式是在定义的时候用列表初始化
A a[5] = {A(1),A(2),A(3),A(4),A(5)};一种方式是在定义了数组对象以后,再使用临时对象进行初始化
A b[5]; b[0] = A(1); b[1] = A(2); b[2] = A(3); b[3] = A(4); b[4] = A(5);
通过构造函数和析构函数可以看出来:
#include<iostream> using namespace std; class A { public: A(int n=0) { i = n; cout<<"================>constructor :"<<i<<endl;; } ~A() { cout<<"================>destructor :"<<i<<endl;; } private: int i; }; int main() { cout<<"=============start test one=============="<<endl; A a[5] = {A(1),A(2),A(3),A(4),A(5)}; cout<<"=============end test one================"<<endl<<endl; cout<<"============start test two================"<<endl; A b[5]; b[0] = A(1); b[1] = A(2); b[2] = A(3); b[3] = A(4); b[4] = A(5); cout<<"==============end test two================="<<endl; return 0; }
原文:http://blog.csdn.net/qsyzb/article/details/18367895