C ++ 11 initializer_list构造函数,带有自定义向量类的头和cpp文件 [英] C++11 initializer_list constructor with header and cpp file for custom vector class
问题描述
我正在做一个学校项目,我在这里构建一个自定义向量类。
类应该能够以几种不同的方式初始化向量。
我遇到了这个initializer_list向量的初始化。
I'm doing a school project where I am to construct a custom vector class. And the class should be able to initialize vectors in a few different ways. I've got stuck with this initializer_list initialization of the vector.
允许作为元素的唯一值是unsigned int。
The only values wich are allowed as elements are unsigned int.
标题
#include <initializer_list>
class myvec {
private:
unsigned int *arr; //pointer to array
std::size_t n; //size of myvec
public:
myvec(); // Default contructor
myvec(std::size_t size); // Creating a vec with # of element as size
myvec(const myvec&); // Copy constructor
myvec(const initializer_list<unsigned int>& list);
cpp
#include "myvec.h"
#include <initializer_list>
myvec::myvec() {
arr = new unsigned int[0];
n = 0;
}
myvec::myvec(std::size_t size) {
arr = new unsigned int[size];
n = size;
}
myvec::myvec(const myvec& vec) {
arr = new unsigned int[vec.n];
n = vec.n;
for (int i = 0; i < vec.n; i++) {
arr[i]=vec.arr[i];
}
}
myvec::myvec(const std::initializer_list<unsigned int> list) {
}
我不明白是怎样的构造函数应该写为它工作?
What I don't understand is how the constructor should be written for it to work? Been trying to find answers on internet for a long time without success.
我想从另一个c ++文件中调用initializer_list构造函数为
test.cpp
I want to call the initializer_list constructor from another c++ file as test.cpp
myvec a = {1,2,3,4};
推荐答案
假设您传递 std :: initializer_list
参数你可以,它是轻量级的),你可以做一些像:
Assuming that you are passing the std::initializer_list
argument by value (and you can, it is lightweight), you could do something like:
myvec(std::initializer_list<unsigned int> l) : myvec(l.size()) {
std::copy(std::begin(l), std::end(l), arr);
}
也就是说,使用 size()
,然后使用 std :: begin()
和 std :: end()
复制其元素。
That is, you initialize your internal array with the size()
of the list, and you iterate over it with std::begin()
and std::end()
to copy over its elements.
这篇关于C ++ 11 initializer_list构造函数,带有自定义向量类的头和cpp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!