结论
今天一反常态,先说结论——会!,探究这个问题的起因是工作中遇到了这个问题。本来记得new一个对象一般情况下会调用这个对象的构造函数,可是一时间记不清楚数组会不会调用了,于是决定试一下.
测试
#include <iostream>
using namespace std;
class CTest
{
public:
CTest ()
{
m_nValue = 11;
cout << "this constructor" << endl;
}
private:
int m_nValue;
};
int main(int argc, char* argv[])
{
cout << "\ndeclare one object in stack:" << endl;
CTest ctest;
cout << "\ndeclare one object in heep:" << endl;
CTest* ptest = new CTest();
cout << "\ndeclare object arrray in stack:" << endl;
CTest artest[3];
cout << "\ndeclare object array in heep:" << endl;
CTest* ptestlist = new CTest[5];
return 0;
}
运行结果
declare one object in stack:
this constructordeclare one object in heep:
this constructordeclare object arrray in stack:
this constructor
this constructor
this constructordeclare object array in heep:
this constructor
this constructor
this constructor
this constructor
this constructor
总结
无论是定义单个的对象还是定义一个对象数组,都会调用对应对象的构造函数,后来想想我应该是把这件事情和operator new与operator new[]的关系弄混了,如果对我的测试结果有什么疑问,欢迎批评指正。
另注
这个问题的测试环境:
- windows + vs2008
- linux + gcc

本文通过实验验证了在C++中无论是定义单个对象还是对象数组,都会调用对应的构造函数。测试覆盖了堆栈和堆上的对象实例化,并提供了详细的运行结果。

被折叠的 条评论
为什么被折叠?



