11

Arrays in the initialization list of a constructor

 2 years ago
source link: https://www.codesd.com/item/arrays-in-the-initialization-list-of-a-constructor.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Arrays in the initialization list of a constructor

advertisements

I'm trying to figure out how to declare an array of an arbitrary size in the constructor's initialization list. If this isn't possible, what should I do instead?

For example:

class vectorOfInt
{
public:

private:
    int _size;
    int _vector[];
};

vectorOfInt::vectorOfInt()
    :_size(32),
    _vector(size)
{
}

Basically, I want the array _vector to be initialized to size (32 in this case). How do I do that? Thanks for any input.


Use an std::vector:

#include <vector>

class vectorOfInt
{
public:

private:
    int _size; // probably you want to remove this, use _vector.size() instead.
    std::vector<int> _vector;
};

vectorOfInt::vectorOfInt()
    :_size(32),
    _vector(size)
{
}

Edit: Since you don't want to use std::vector, you'll have to handle memory yourself. You could use a built-in array if you knew the size of the array at compile time, but I doubt this is the case. You'd have to do something like:

#include <memory>

class vectorOfInt
{
public:

private:
    int _size;
    // If C++11 is not an option, use a raw pointer.
    std::unique_ptr<int[]> _vector;
};

vectorOfInt::vectorOfInt()
    :_size(32),
    _vector(new int[size])
{
}




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK