簡體   English   中英

為什么不能從初始化列表初始化我的類,即使它派生自 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}};
一切正常。
跆拳道?

有兩種方式:

  1. 不要從標准類繼承,而是使用typedef

     typedef std::pair<unsigned int, unsigned int> Pair; typedef std::list<Pair> PairList;
  2. 在繼承的類中實現正確的構造函數(將std::initializer_list作為參數),基類構造函數不能自動使用。

我推薦第一種選擇,因為標准類(除了少數例外)不是為了繼承設計的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM