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

mey*_*ani 6 c++ constructor class stdvector c++11

我想先制作一个没有大小(vector<int> times)的向量,然后再在类()的构造函数中定义其大小times(size)

我可以通过使用初始化器列表来做到这一点,如下所示

class A (int size): times(size) {};
Run Code Online (Sandbox Code Playgroud)

但是我的问题是,为什么不能在类似于以下代码的类的构造函数中执行此操作?

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

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

A::A(int size)
{
    line(size);// here I got the error
}
Run Code Online (Sandbox Code Playgroud)

line(size) 犯错误

JeJ*_*eJo 7

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

A::A(int size)
{
    line.resize(size);
}
Run Code Online (Sandbox Code Playgroud)

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

更好的方法是使用成员初始值设定项列表,这将有助于从传递的大小构造向量,并0在到达构造函数主体之前使用进行初始化。

A(int size) : line(size) {}
Run Code Online (Sandbox Code Playgroud)

它使用以下的构造函数 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)
Run Code Online (Sandbox Code Playgroud)