Initialize class object like an array

2020-05-02 04:26发布

I'm creating a custom vector class for a school project and I'd like to be able to initialize it like this:

vector x = { 2, 3, 4, 5 };

Is there any way to do this is C++?

Here is the header of my class:

class vector {
private:

    int vsize;
    int valloc;
    double* values;

public:

    vector() : vsize(0), valloc(0), values(nullptr) {}
    vector(???);
    vector(const vector& v);
    int size() const { return vsize; };
    int alloc() const { return valloc; };
    void resize(int newsize);
    void insert(double x);
    void insert(double x, int index);
    double* value() const { return values; };
    double value(int index) const { return *(values + index - 1); }

};

1条回答
唯我独甜
2楼-- · 2020-05-02 05:07

You can support that by adding a constructor that takes a std::initialzer_list<double>.

vector(std::initializer_list<double> init) : vsize(init.size()),
                                             valloc(init.size()),
                                             values(new double[init.size()])
{
   std::copy(init.begin(), init.end(), values);
}

You can make that a bit more flexible by using a template.

template <typename T>
vector(std::initializer_list<T> init) : vsize(init.size()),
                                        valloc(init.size()),
                                        values(new double[init.size()])
{
   std::copy(init.begin(), init.end(), values);
}
查看更多
登录 后发表回答