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

标签 c++ c++11 initializer-list 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}};
}

我使用 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}};
一切正常。
什么鬼?

最佳答案

有两种方式:

  1. 不要从标准类继承,而是使用 typedef:

    typedef std::pair<unsigned int, unsigned int> Pair;
    typedef std::list<Pair> PairList;
    
  2. 在继承类中实现正确的构造函数(以 std::initializer_list 作为参数),基类构造函数不能自动使用。

我推荐第一种选择,因为标准类(除了少数异常(exception))不是设计为可继承的。

关于c++ - 为什么不能从初始化列表初始化我的类,即使它是从 std::list 派生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13415501/

相关文章:

c++ - 试图理解§3.3.1/4

c++ - Valgrind 错误 : in use at exit: 72, 704 字节 C++ 初始化列表异常与 char*

c++ - 从成员初始化列表中调用普通的 void 函数?

c++ - 如何使用自定义运算符<<创建折叠表达式?

c++ - 是否可以#include 命名空间类到另一个命名空间

c++ - 为什么不能在 C++11 中将非虚拟方法定义为 final?

c++ - 具有未定义成员函数返回类型的模板实例化

c++ - 如何在 C++ 初始化列表中初始化指针数组

c++ - 多个子进程的 PID 从同一个父进程中 fork 出来

c++ - Qt Creator中如何访问其他ui文件