为什么不能从初始化列表初始化我的类,即使它派生自std :: list?

时间:2012-11-16 11:16:18

标签: c++ c++11 initializer-list list-initialization

我有以下代码。

#include <utility>
#include <list>
#include <iostream>

class Pair: public std::pair<unsigned int, unsigned int>{
    Pair (unsigned int h, unsigned int l) : pair(h,l){};
};
class PairList: public std::list<Pair>{};


int main(int argc, char** argv){

    PairList pl = {{800,400},{800,400}};
}

我使用命令行
使用minGW g ++ v4.6编译它 g++ -std=c++0x Test.cpp -o test.exe
并得到错误:
error: could not convert '{{800, 400}, {800, 400}}' from '<brace-enclosed initializer list>' to 'PairList'
但如果在main()我写了 list<pair<unsigned int,unsigned int>> pl = {{800,400},{800,400}};
一切正常。
WTF?

1 个答案:

答案 0 :(得分:6)

有两种方法:

  1. 不要继承标准类,而是使用typedef

    typedef std::pair<unsigned int, unsigned int> Pair;
    typedef std::list<Pair> PairList;
    
  2. 在继承的类中实现正确的构造函数(以std::initializer_list作为参数),基类构造函数不能自动使用。

  3. 我建议使用第一种方法,因为标准类(少数例外)设计为继承。

相关问题