C++ alloc对象数组

Iul*_*urt 0 c++ memory-management

我有一个问题,我需要用一些构造函数初始化一些对象的数组.让我说明我的意思:

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
}
Run Code Online (Sandbox Code Playgroud)

我需要在wrong标记线上提供一些帮助.如何分配该阵列的每个成员?

谢谢你没有把我指向其他帖子(我在帖子之前看了很多)

Eri*_*rik 5

摆脱fileName变量并使用out[i].open(str.c_str());- 并记住delete[] out;


Chr*_*s K 5

这是解决您问题的最简单方法.

out[i].open(fileName); 
Run Code Online (Sandbox Code Playgroud)