在向量初始化中为对象调用非默认构造函数

时间:2010-11-24 13:32:22

标签: c++ constructor vector initialization parameter-passing

我想在构造函数的初始化列表中初始化一个向量。向量由具有参数化构造函数的对象组成。我所拥有的是:

Class::Class() : 
   raster_(std::vector< std::vector<Cell> > (60, std::vector<Cell>(80)))
{
...

如何在上面一行中使用两个参数调用Cell :: Cell?显而易见:

raster_(std::vector< std::vector<Cell(true,true)> > (60, std::vector<Cell(true,true)>(80)))

没用。

2 个答案:

答案 0 :(得分:2)

你应该尝试:

Class::Class() : 
     raster_(60, std::vector<Cell>(80, Cell(true, true)))
{
    /* ... */
}

请注意,我从初始化程序中删除了无用的std::vector<std::vector<Cell> >。另请注意,根据复制Cell

的成本,这可能非常无效
  • 通过复制提供值std::vector<Cell>
  • 的80倍来创建Cell(true, true)
  • 通过复制60次提供的向量(其中包含80个元素)来创建std::vector<std::vector<Cell> >

答案 1 :(得分:1)

:raster_(std::vector< std::vector<Cell> > (60, std::vector<Cell>(80, Cell(true, true))));

如果raster_是采用向量的东西。如果raster_本身是矢量,那么就像这样

:raster(60, std::vector<Cell>(80, Cell(true, true)))

相关问题