使用new运算符会调用对象的构造函数
class test
{
private:
/* data */
public:
int val = 0;
test(/* args */);
~test();
};
test::test(/* args */)
{
val = 100;
}
主函数:
int main(int argc, char* argv[]) {
test* testArr = new test[10];
for (int i = 0; i < 10; i++)
{
std::cout<< i << " is "<< testArr[i].val << std::endl;
}
delete [] testArr;
return 0;
}
结果:
0 is 100
1 is 100
2 is 100
3 is 100
4 is 100
5 is 100
6 is 100
7 is 100
8 is 100
9 is 100