我有以下代码。
#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}};
}
我使用v4.6的MinGW g++和命令行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?
有两种方法:
-
不要从标准类继承,而是使用
typedef
:typedef std::pair<unsigned int, unsigned int> Pair; typedef std::list<Pair> PairList;
-
在继承的类中实现正确的构造函数(以
std::initializer_list
为参数),基类构造函数不能自动使用。
我推荐第一种选择,因为标准类(除了少数例外)是而不是设计为继承的。