简体   繁体   中英

How to make a constructor with std::initializer_list<double>

I'm currently learning about classes and constructors.

class Container
{

....

public:
    // constructors
    Container() {
        length = 0;
        data = nullptr;
        print("default constructor");}

    Container(int lenght){
        data = new double[lenght];
    }


   // destructor

    // operators
    void print(const std::string& info) const
    {
        // print the address of this instance, the attributes `length` and
        // `data` and the `info` string
        std::cout << "  " << this << " " << length << " " << data << "  "
            << info << std::endl;
    }

private:
    int length;
    double* data;
};

I already made two constructors. I need to make an additional constructor. I got the following instruction.

Create a constructor that takes an std::initializer_list. The list contains values for the data array. Use constructor delegation to set the length of this container and allocate data. Then copy all elements of the list to data.

I have trouble with construction delegation. Because if the new constructor takes in a argument. How does the previous construction that I need to delegate the length (Since the only input variable is a int)?. Besides I'm confused about the allocating and copying of the data.

Could somebody give me an example to help me tackle this problem?

Thanks, Nadine:)

Delegating is similar to using the member initializer list.

Example:

#include <algorithm>         // std::copy
#include <initializer_list>

// ...

    Container(std::initializer_list<double> il) :
        Container(il.size())  // delegate to  Container(int length)
    {
        std::copy(il.begin(), il.end(), data); // copy the data
    }

Also note that the constructor it delegates to currently does not save the length. You could rewrite it like this:

    Container(int len) : // use the member initializer list
        length(len),
        data(new double[length])
    {
    }

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