如何在class的构造函数中定义成员向量的大小?

How to define the size of member vector in constructor of a class?

我想先创建一个没有大小的向量 (vector<int> times),然后我想在 class 的构造函数中定义它的 大小 ( times(size) ).

我可以使用初始化列表来完成,如下所示

class A (int size): times(size) {};

但我的问题是,为什么我不能像下面的代码那样在 class 的构造函数中执行此操作?

我的意思是为什么下面的代码是错误的?

class A
{
public:
    A(int size);
private:
    std::vector<int> line;
};

A::A(int size)
{
    line(size);// here I got the error
}

line(size)出错

您可以为此使用成员函数std::vector::resize

A::A(int size)
{
    line.resize(size);
}

成员 line 将在到达构造函数主体之前被默认构造(即 std::vector<int> line{})。因此写 line(size); 没有意义,因此 编译器错误。

使用 member initializer lists 会更好,这会有所帮助 在到达构造函数主体之前,根据传递的大小构造向量并使用 0 进行初始化。

A(int size) : line(size) {}

它使用了std::vector

的以下构造函数
explicit vector( size_type count );   // (since C++11)(until C++14)
explicit vector( size_type count, const Allocator& alloc = Allocator() ); // (since C++14)

您可能想使用 initializer list:

A::A(int size) : line(size)
{ }

或将 new value 分配给 line:

A::A(int size)
{
  this->line = std::vector(size);
}

这两个选项将向向量中插入 size 个元素。因此向量将填充默认值。如果您只想确保有足够的 space 在稍后的时间点插入那么多元素,请使用 reserve 来增加已构建向量的容量:

A::A(int size)
{
  this->line.reserve(size);
}

澄清

如果您使用第一个或第二个选项 line.size()line.capacity() 将等于 size,因为默认元素已插入向量中。
使用第三个选项,将不会插入默认元素,因此 line.size() 将为 0 并且 line.capacity()size.

代码错误,因为您试图在构造函数的主体中 re-initialize 一个已经初始化为大小 0 的向量。

更改您的构造函数代码以使用初始化列表

A::A(int size)
  : line(size)
{
}