1

最初,我有一些看起来像的代码

class Ball
{
public:
    double x , y ;
    ofstream out ;
} ;

int main()
{
    Ball array[N] ;

    array[0].out.open("./position_1.txt") ;
    array[1].out.open("./position_2.txt") ;

    ......
}

其中 N 是运行时确定的常数。但它最近遇到了可变长度数组问题。

我尝试遵循这篇文章的建议Can't set variable length with variable by using STL container。

int main()
{
    vector<Ball> Balls ;
    Ball b ;

    b.out.open( "./position_1.txt" ) ;
    Balls.push_back( b ) ;
    ......
}

它在 失败push_bak(),因为无法复制流。

在运行之前我无法确定球的数量,我必须存储文件流而不是路径以提高效率(防止打开和关闭文件)。

有什么方法可以实现目标吗?谢谢

4

3 回答 3

3

C++ 流不可复制,但它们是可移动的,因此您可以这样做:

Balls.push_back( std::move(b) );

//DO NOT use b after push_back, as it has been moved!

并且编译器为您的类生成的默认移动语义可以正常工作。

在 C++11 中,你可以这样写:

std::vector<Ball> balls(N); //N is known at runtime

balls[i].out.open( "./position_1.txt" ); //i <= i < N

Note that this will not work in C++03, as in C++03 vector's constructor creates N copies of a default created object of type Ball. In C++11, however, it doesn't make any copy!

于 2013-02-06T07:55:52.107 回答
1

If your compiler/library are old enough that they don't support move semantics for streams yet (many don't) you might consider storing a (smart) pointer to a stream in the structure instead. You do probably want it to be a smart pointer though -- handling ownership transfer correctly on your own is likely to be quite a bit of work to get right.

于 2013-02-06T08:02:23.707 回答
0

Then make Balls a vector of pointers to Ball. Allocate the Ball objects with new and push_back the pointers.

Note that, if you use simple pointers, you must delete the Ball objects at the end with a loop. You can avoid this by using smart pointers, like std::tr1::shared_ptr.

于 2013-02-06T08:04:23.950 回答