[英]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:有两种方式:
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;
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.