![](/img/trans.png)
[英]Why can't I initialize an ifstream in the initializer list of the constructor of a class?
[英]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}};
一切正常。
跆拳道?
有兩種方式:
不要從標准類繼承,而是使用typedef
:
typedef std::pair<unsigned int, unsigned int> Pair; typedef std::list<Pair> PairList;
在繼承的類中實現正確的構造函數(將std::initializer_list
作為參數),基類構造函數不能自動使用。
我推薦第一種選擇,因為標准類(除了少數例外)不是為了繼承而設計的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.