简体   繁体   English

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

[英]Why can't initialize my class from an initializer list even if it derives from std::list?

I have the following code.我有以下代码。

#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}};
}

I compile it using MinGW g++ of v4.6 with the command line我在命令行中使用 v4.6 的 MinGW g++ 编译它
g++ -std=c++0x Test.cpp -o test.exe
and got the error:并得到错误:
error: could not convert '{{800, 400}, {800, 400}}' from '<brace-enclosed initializer list>' to 'PairList'
But if in main() I write但是如果在 main() 我写
list<pair<unsigned int,unsigned int>> pl = {{800,400},{800,400}};
all works fine.一切正常。
WTF?跆拳道?

There are two ways:有两种方式:

  1. Don't inherit the from the standard classes, use typedef instead:不要从标准类继承,而是使用typedef

     typedef std::pair<unsigned int, unsigned int> Pair; typedef std::list<Pair> PairList;
  2. Implement the correct constructors in your inherited classes (takingstd::initializer_list as argument), the base class constructors can't be used automatically.在继承的类中实现正确的构造函数(将std::initializer_list作为参数),基类构造函数不能自动使用。

I recommend the first alternative, as the standard classes (with few exceptions) are not designed to be inherited.我推荐第一种选择,因为标准类(除了少数例外)不是为了继承设计的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么不能在类的构造函数的初始化列表中初始化ifstream? - Why can't I initialize an ifstream in the initializer list of the constructor of a class? 使用初始化列表初始化类中的std :: ofstream - Initialize a std::ofstream in a class using initializer list 在类的成员初始化器列表中初始化std :: tuple - Initialize std::tuple in member initializer list of a class 在类的初始化器列表中初始化std :: vector - Initialize std::vector in class's initializer list 为什么不能在派生类的构造函数初始化列表中初始化基类的数据成员? - Why can't Initialize the data member of base class in the constructor initializer list of derived class? 从 std::array 私有继承时无法从 std::initializer_list 构造 - Can't construct from std::initializer_list when privately inheriting from std::array 为什么我不能使用统一初始化初始化初始化列表中的引用? - Why can't I initialize a reference in an initializer list with uniform initialization? Clang为什么不能优化std :: initializer_list? - Why can't Clang optimise away std::initializer_list? 从构造函数参数初始化类初始化列表中的const多维数组 - Initialize const multidimensional array in class initializer list from constructor arguments 使用std :: initializer_list初始化类/结构内的容器 - Initialize a container inside a class/struct with std::initializer_list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM