Ole*_*egG 1 c++ initializer-list c++11 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}};
}
Run Code Online (Sandbox Code Playgroud)
我使用命令行使用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?
有两种方法:
不要从标准类继承,typedef而是使用:
typedef std::pair<unsigned int, unsigned int> Pair;
typedef std::list<Pair> PairList;
Run Code Online (Sandbox Code Playgroud)在继承的类中实现正确的构造函数(std::initializer_list作为参数),基类构造函数不能自动使用.
我推荐第一种替代方案,因为标准类(少数例外)不是为了继承而设计的.
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |