简体   繁体   中英

Use constructor to initialize array (C++)

How do I initialize an array through a constructor? Here is the code for a class called Sort:

private:
    double unpartitionedList[]; 

public:
    Sort(double unpartitionedList[]);

Sort::Sort(double unpartitionedList[])
{
    this->unpartitionedList = unpartitionedList;
}

I'd like to be able to pass an array to the constructor and have it stored in unpartitionedList[] . Like this: Sort(array[])

As the code is now, I get a compiler error in DevC++:

"[Error] incompatible types in assignment of 'double*' to 'double[0]'"

I've tried inserting reference ( & ) and dereference ( * ) operators where I thought they were needed, but unfortunately, my attempts were unsuccessful.

Any suggestions would be greatly appreciated.

Arrays aren't assignable. You'll have to do an element-wise copy or write actual C++ code and use std::array or std::vector .

class Sort
{
private:
    double unpartitionedList[]; 

public:
    Sort(double unpartitionedList[]);
};

Sort::Sort(double unpartitionedList[])
{
    this->unpartitionedList = unpartitionedList;
}

That code will not compile as arrays are not assignable. You can accomplish your goal a few different ways (depending on the requirements you haven't mentioned).

Method 1: Manual Memory Management

class Sort
{
private:
    double* unpartitionedList;
    std::size_t _size; 

public:
    Sort(double* upl, std::size_t n);
};

Sort::Sort(double* upl, std::size_t n) : unpartitionedList(upl), _size(n)
{

}

There are a few things to note here: If you intend for this class to take ownership of the memory, you will have to properly manage it (eg free the memory in the destructor, and provide a proper copy-constructor that will perform a deep-copy). Because of the memory management requirements, this method is not recommended if not absolutely necessary.

Method 2/3: STD Containers

class Sort
{
private:
    std::vector<double> _upl;
    // or 
    // std::array<double, SIZE> upl; // with a constant SIZE defined

public:
    Sort(const std::vector<double>& upl);
};

Sort::Sort(const std::vector<double>& upl) : _upl(upl)
// Sort::Sort(const std::array<double, SIZE>& upl) : _upl(upl)
{

}

This will remove the memory management requirement. std::vector will allow you to size the array at runtime. std::array is a thin wrapper around a C-style array (and must be sized at compile time).

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