最近由于需要頻繁使用Dictionary,于是就動手實現了一個,希望和List可以隨意地換來換去。
//IList.h
template<typename _Type>
class IIList : public ICollection<_Type>{
};
//List.h
template<typename _Type>
class List : public IList<_Type>{
};
//IDictionary.h
template<typename TKey, typename TValue>
class IDictionary : public ICollection<Pair<TKey, TValue>>{
};
我希望IDictionary.h提供一個ToList() GetKeys() GetValues() 的操作,如果返回IList:
error C2682: cannot use 'dynamic_cast' to convert from 'const Lyt::Collection::List<_Type> *' to 'Lyt::Collection::IList<_Type> *' e:\c++\library\library\library\collection\dictionary.h 171
為啥會有編譯錯誤,至今不明,明明List繼承了IList怎么還會轉換失敗= =
還有另外一個問題,在實現GetKeys()時,我希望是返回IList而非List,這樣如果我以后有其他關于List的實現就不需要修改代碼了,考慮到內存泄漏的問題,我只想到兩種解決方法,不知道到底怎么折騰才合適,求解答。
//方法一
#include "List.h"
template<typename TKey, typename TValue>
class Dictionary : public IDictionary<TKey, TValue>
{
protected:
List<Pair<TKey, TValue>> Data;
public:
AutoPtr<IList<Pair<TKey, TValue>>> GetKeys()const
{
AutoPtr<IList<Pair<TKey, TValue>>> Result=new List<TKey>; //用引用計數實現的智能指針
/**/
}
};
//方法二
#include "List.h"
template<typename TKey, typename TValue>
class Dictionary : public IDictionary<TKey, TValue>
{
protected:
List<Pair<TKey, TValue>> Data;
List<TKey> Keys; //本來我只需要一個List來存放東西就夠了,這樣我在其他的Add、Remove等操作中都要多折騰一個Keys,是不是沒有必要?
public:
const IList<TKey>* GetKeys()const
{
return dynamic_cast<IList<TKey>*>(&Keys);
}
};
posted on 2009-10-15 09:44
Lyt 閱讀(1452)
評論(5) 編輯 收藏 引用 所屬分類:
數據結構