对象的C ++ alloc数组

问题描述

| 我遇到了一些我需要用一些构造函数初始化的对象数组的分配问题。让我表明我的意思:
ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << \"file\" << i << \".txt\";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now,this is wrong
}
我需要ѭ1标记行的帮助。如何分配该数组的每个成员? 并感谢您没有将我指向其他帖子(发布前我看了很多东西)     

解决方法

摆脱
fileName
变量并使用
out[i].open(str.c_str());
-并记住
delete[] out;
    ,这是您问题的最简单解决方案。
out[i].open(fileName); 
    ,您可以删除
str
fileName
来优化此设置:
out[ i ].open( ss.str().c_str() );
另外,我建议您不要使用ѭ9来进行内存分配和释放。
std::vector< std::ofstream >
    ,如果您确实需要在插入元素时调用构造函数(可能是因为您的类没有默认的构造函数),请尝试按此处所述放置新的http://www.parashift.com/c++-faq- lite / ctors.html#faq-10.5