括号括起的初始化程序列表构造函数

我有以下构造函数的类Phenotype:


Phenotype(uint8 init[NUM_ITEMS]);

我可以创建这样的表型:


uint8 data[] = {0,0,0,0,0};

Phenotype p(data);

但是当我尝试创建一个这样的错误消息:


Phenotype p = {0,0,0,0,0};

输出:


$ make

g++ -Wall -g main.cpp -std=c++0x

main.cpp: In function ‘int main(int, char**)’:

main.cpp:109: error: no matching function for call to ‘Phenotype::Phenotype(<brace-enclosed initializer list>)’

main.cpp:37: note: candidates are: Phenotype::Phenotype(uint8*)

该错误似乎表明存在一种定义带括号括起的初始化程序列表的构造函数的方法。有谁知道该怎么做?


梦里花落0921
浏览 563回答 3
3回答

拉莫斯之舞

只能对聚合(数组和某些类。与流行的看法相反,这也适用于许多非荚)。编写带它们的构造函数是不可能的。由于您将其标记为“ C ++ 0x”,因此这是可能的。神奇的词是“ initializer-list构造函数”。这就像Phenotype(std::initializer_list<uint8> c) {&nbsp; assert(c.size() <= std::size(m_array));&nbsp; std::copy(c.begin(), c.end(), m_array);}// used likePhenotype p1{1, 2, 3};Phenotype p2({1, 3, 2}); // works tooPhenotype p3(1, 2, 3); // doesn't work但是,此类初始化将默认构造数组,然后使用赋值运算符。如果您追求速度和安全性(太多初始化器会导致编译时错误!),那么您也可以将普通构造函数与可变参数模板一起使用。不过,这可能比需要的通用(通常initializer_list完全足够,特别是对于纯整数)。它得益于完美的转发,因此可以将右值参数移动到数组元素中template<typename ...T>Phenotype(T&&...t):m_array{ std::forward<T>(t)... } {}// used likePhenotype p1{1, 2, 3};&nbsp;Phenotype p2(1, 2, 3); // works tooPhenotype p3({1, 2, 3}); // doesn't work&nbsp; &nbsp;这是一个艰难的选择!编辑更正,最后一个也可以,因为我们没有构造构造函数explicit,因此它可以使用的copy构造函数Phenotype,构造一个临时Phenotype对象并将其复制到p3。但这不是我们真正希望的电话:)

隔江千里

在C ++ 0x中,您似乎可以为此创建一个构造函数。我自己对此没有经验,但是看起来它像称为Initializer list-constructor。容器可以实现如下的初始化列表构造函数:template<class E> class vector {public:&nbsp; &nbsp; vector (std::initializer_list<E> s) // initializer-list constructor&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; reserve(s.size());&nbsp; // get the right amount of space&nbsp; &nbsp; &nbsp; &nbsp; uninitialized_copy(s.begin(), s.end(), elem);&nbsp; &nbsp;// initialize elements (in elem[0:s.size()))&nbsp; &nbsp; &nbsp; &nbsp; sz = s.size();&nbsp; // set vector size&nbsp; &nbsp; }&nbsp; &nbsp; // ... as before ...};

森栏

您需要使用std :: initializer_list模板类型。例:#include <iostream>class X {&nbsp; &nbsp; public:&nbsp; &nbsp; &nbsp; &nbsp; X (std::initializer_list<int> list) {&nbsp; &nbsp; &nbsp; &nbsp; for (auto i = list.begin(); i != list.end(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::cout << *i << std::endl;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }};int main () {&nbsp; &nbsp; X x = {1,2,3,4,5};}
打开App,查看更多内容
随时随地看视频慕课网APP