C ++初始化模板类

时间:2013-01-01 20:51:33

标签: c++ templates vector

当我创建模板类时,我对于发生的事情感到有些困惑。我正在尝试在构造期间将成员vector_的容量设置为50(仅一次),但似乎容量从未正确设置,所以显然我不明白应该如何完成。我已经包含了相关的代码片段以及控制台输出。谢谢你的帮助!

vector的模板类:

template <typename T>
class V
{
  public:
    V()
    {
      std::cout << "capacity 1 = " << this->vector_.capacity() << "\n";
    };
    V(int capacity)
    {
      this->vector_.reserve(capacity);
      std::cout << "capacity 2 = " << this->vector_.capacity() << "\n";
    };
    int capacity() const { return this->vector_.capacity(); };
  private:
    std::vector<T> vector_;
};

R初始化的构造函数:

R::R()
{
  std::cout << "capacity 0 = " << this->s_.capacity() << "\n";
  this->s_ = V< std::vector< std::complex<float> > >(50);
  std::cout << "capacity 3 = " << this->s_.capacity() << "\n";
};

R类标题:

class R
{
  public:
    R();
  private:
    V< std::vector< std::complex<float> > > s_;
};

输出到控制台:

capacity 1 = 0
capacity 0 = 0
capacity 2 = 50
capacity 3 = 0

1 个答案:

答案 0 :(得分:4)

您没有设置std::vector<T>的大小,而是设置其容量。容量不是std::vector<T>的显着属性,因此不会被复制。您需要使用resize()来设置大小。