您可以在同一行声明和初始化常规数组,如下所示:
int PowersOfTwo[] = {1, 2, 4, 8, 16, 32, 64, 128};
有没有办法在自定义类中复制这种行为?所以,例如:
MyClass<int> PowersOfTwo = {1, 2, 4, 8, 16, 32, 64, 128};
您可以让复制构造函数将数组作为其参数,但您仍然必须在上一行声明该数组。
int InitializationArray[] = {1, 2, 4, 8, 16, 32, 64, 128};
MyClass<int> PowersOfTwo = InitializationArray;
最佳答案
你可以这样来实现你的类:
MyClass<int> array;
array = 1,2,3,4,5,6,7,8,9,10;//dont worry - all ints goes to the array!!!
这是我的实现:
template <class T>
class MyClass
{
std::vector<T> items;
public:
MyClass & operator=(const T &item)
{
items.clear();
items.push_back(item);
return *this;
}
MyClass & operator,(const T &item)
{
items.push_back(item);
return *this;
}
size_t Size() const { return items.size(); }
T & operator[](size_t i) { return items[i]; }
const T & operator[](size_t i) const { return items[i]; }
};
int main() {
MyClass<int> array;
array = 1,2,3,4,5,6,7,8,9,10;
for (size_t i = 0 ; i < array.Size() ; i++ )
std::cout << array[i] << std::endl;
return 0;
}
输出:
1
2
3
4
5
6
7
8
9
10
参见在线演示:http://www.ideone.com/CBPmj
你可以在这里看到我昨天发布的两个类似的解决方案:
Template array initialization with a list of values
编辑:
您可以使用类似的技巧来填充现有的 STL 容器。例如,你可以这样写:
std::vector<int> v;
v+=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //push_back is called for each int!
所有你需要重载 ()
和 ,
运算符为:
template<typename T>
std::vector<T>& operator+=(std::vector<T> & v, const T & item)
{
v.push_back(item); return v;
}
template<typename T>
std::vector<T>& operator,(std::vector<T> & v, const T & item)
{
v.push_back(item); return v;
}
再次编辑:
我是 having fun with C++ operator .现在:
std::vector<int> v;
v << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //inserts all to the vector!
我觉得这样更好看!
关于c++ - 实现数组初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5395595/