[英]How can I get my array class instance to use initializer list to initialize the array
I am trying to write an array class similar to the one in standard lib for practice.我正在尝试编写一个类似于标准库中的数组 class 以进行练习。 I want to be able to initialize my array class by using an initializer list, but I don't what code to add to my class to do that.我希望能够通过使用初始化列表来初始化我的数组 class,但我没有添加到我的 class 的代码来执行此操作。 I am confused because there are multiple elements in the initializer list but only container to hold the data.我很困惑,因为初始化列表中有多个元素,但只有容器来保存数据。
#include <iostream>
template<typename T, int size>
class Array
{
private:
T data[size];
public:
Array() {};
};
int main()
{
//I want to do this but it currently doesn't allow me to do this.
//I need someone to tell me what i need to add to my class to be able
//to do this
//Aarray<int, 5> a{1, 2, 3, 4, 5};
//The above line should do
//a.data[0] = 1;
//a.data[1] = 2;
//a.data[2] = 3;
//a.data[3] = 4;
//a.data[4] = 5;
}
There are several ways有几种方法
make your class aggregate:使您的 class 聚合:
template<typename T, int size> class Array { public: T data[size]; };
Provide constructor which accept {..}
such as提供接受{..}
的构造函数,例如
template<typename T, int size>
class Array
{
private:
T data[size];
public:
Array(const T (&data)[size]);
//Array(std::initializer_list<T> ini);
// ...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.