简体   繁体   中英

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

I want to make a vector first without a size ( vector<int> times ) and I want to define its size later in a constructor of a class ( times(size) ).

I can do it by using the initializer list as you see below

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

But my question is that why I can not do it in a constructor out of a class like the code below?

I mean why the code below is wrong?

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

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

line(size) make an error

You can use the member function std::vector::resize for that

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

The member line will be default constructed(ie std::vector<int> line{} ) before reaching the body of the constructor. And hence writing line(size); makes no sense, hence the compiler error.

Much better would be using the member initializer lists , which will help to construct the vector from the size passed and initialize with 0 's, before reaching the constructor body.

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

It uses the following constructor of 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)

You probably want to either use an initializer list :

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

or assign a new value to line :

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

These two options will insert size elements into the vector. So the vector will be filled with default values. If you only want to make sure there is enough space to insert that many elements on a later point in time use reserve to increase capacity of the already constructed vector:

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

Clarification

If you use the first or second option line.size() and line.capacity() will be equal size , because default elements have been inserted into the vector.
With the third option, no default elements will be inserted, so line.size() will be 0 and line.capacity() is size .

The code is wrong because you attempted to re-initialize in the body of your constructor a vector that was already initialized to size 0.

Change your constructor code to use the initializer list

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM