为什么不能从初始值设定项列表初始化我的类,即使它派生自 std::list?
Why can't initialize my class from an initializer list even if it derives from std::list?
我有以下代码。
#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
为参数),基类构造函数不能自动使用。
我推荐第一种选择,因为标准类(除了少数例外)是而不是设计为继承的。
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- C++中带有List类的迭代器Segfault
- 使用"std::unordereded_map"映射到"std::list"对象
- GCC对可能有效的代码抛出init list生存期警告
- 如何使用单独文件中的派生类访问友元函数对象
- 派生类销毁的最佳实践是什么
- 抽象和派生与std::list相结合
- 如何将 std::list of 派生类而不是 std::list of parent class 传递给函数
- 为什么不能从初始值设定项列表初始化我的类,即使它派生自 std::list?
- 将派生类的对象保存在基 c 的 std::list 中
- 通过 BaseClass List 调用派生类对象的析构函数
- 访问 std::list 中派生类的属性
- std::list static_cast派生迭代器