Initialize class object like an array

后端 未结 1 1831
夕颜
夕颜 2021-01-27 20:36

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 the

相关标签:
1条回答
  • 2021-01-27 21:03

    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);
    }
    
    0 讨论(0)
提交回复
热议问题