我正在尝试编写一个类似于标准库中的数组类以供练习。我希望能够通过使用初始化列表来初始化我的数组类,但我不知道要向我的类添加什么代码来做到这一点。我很困惑,因为初始化列表中有多个元素,但只有容器来保存数据。
#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;
}
答案 0 :(得分:0)
有几种方法
让你的班级聚合:
template<typename T, int size>
class Array
{
public:
T data[size];
};
提供接受 {..}
的构造函数,例如
template<typename T, int size>
class Array
{
private:
T data[size];
public:
Array(const T (&data)[size]);
//Array(std::initializer_list<T> ini);
// ...
};