C++中关于构造函数有参数的对象很简单`
Test *a = new Test(1);
但是C++中关于构造函数有参数的对象数组的使用却不是那么友好
以下为对C++中关于构造函数有参数的对象数组的使用的几种方法
class Test
{
public:
int id;
Test(int i)
{
id = i;
}
~Test()
{
cout << "ID: " << id << " destruction function is invoked!" << endl;
}
};
//方法一
Test t1[3] = {Test(1),Test(1),Test(1)};//栈中分配,数组型对象
方法二
Test *t1 = new Test[3]{1,1,1};//栈中分配,数组型对象
delete[] t1;
很多人可能会怀疑方法二行不行,我可以怎么说,在C++11标准中,他已经实现了,但在这之前的标准中,其运行会报警告,析构函数无法运行