2015-11-05 32 views
1

我想重載下標運算符以便使用它來 填充地圖類中使用的模板。C++模板和重載下標運算符

這是模板結構

template<typename K, typename V> 
    struct Node 
    { 
     V  Value; 
     K  Key; 
    }; 

正是在這樣的課堂上使用

地圖類

template<typename K, typename V> 
class myMap 
{ 
public: 
    myMap(); 
    ~myMap(); 

    V& operator[] (const K Key); 

private: 
    const int  mInitalNumNodes = 10; //Start length of the map 
    int    mNumOfNodes;   //Count of the number of Nodes in the map 
    int    mCurrentPostion; 
    Node<K,V>  mNodeList[10]; 
}; 

我想重載下標操作,使我可以把一個關鍵和一個價值通過這個函數調用進入mNodeList。

類和話務員呼叫

myMap<char, int> x; 
x[1] = 2; 

我如何過繼續讓我的超載執行錯誤,你能指出我在正確的方向。

運算符重載

template<typename K, typename V> 
inline V& myMap<K, V>::operator[](const K Key) 
{ 
    // TODO: insert return statement here 
    Node<K, V> newNode; 
    newNode.Key = Key; 

    mNodeList[mCurrentPostion] = newNode; 
    mCurrentPostion++; 
    return mNodeList[&mCurrentPostion-1]; 
} 

錯誤:

非法索引不允許

初始化不能從初始化轉換爲節點

+3

'節點 newNode = {newNode.Key =鍵,};'Ehrm ...什麼? –

+3

這個問題不是關於下標操作符,而是關於結構初始化的問題。如果您相應地編輯標題並減少問題,您可能會得到更好的答案。 (即@SimonKraemer指出的問題也應該是另一種情況下的問題。) – anderas

+0

是的,我修正了這個問題,它仍然是下標操作符不工作 – Lawtonj94

回答

1

你的回報是錯誤的。你最想

return mNodeList[mCurrentPostion - 1].Value; 

,而不是

return mNodeList[&mCurrentPostion-1]; 

MCVE:

template<typename K, typename V> 
struct Node 
{ 
    K  Key; 
    V  Value; 
}; 

template<typename K, typename V> 
class myMap 
{ 
public: 
    myMap() 
     :mCurrentPostion(0) 
     ,mNumOfNodes(0) 
    {} 
    ~myMap() {} 

    V& operator[] (const K Key); 

private: 
    const int  mInitalNumNodes = 10; //Start length of the map 
    int    mNumOfNodes;   //Count of the number of Nodes in the map 
    int    mCurrentPostion; 
    Node<K, V>  mNodeList[10]; 
}; 


template<typename K, typename V> 
inline V& myMap<K, V>::operator[](const K Key) 
{ 
    // TODO: insert return statement here if Key already exists 
    Node<K, V> newNode; 
    newNode.Key = Key; 
    mNodeList[mCurrentPostion] = newNode; 
    mCurrentPostion++; 
    return mNodeList[mCurrentPostion - 1].Value; 
} 

int main() 
{ 
    myMap<char, int> x; 
    x[1] = 2; 
} 
+0

我試過,我已經試過,我已經不能從節點轉換爲int&,但是我還想返回該數組的位置,因爲這是我要分配值的節點所在的位置 – Lawtonj94

+0

也許你應該更新你的問題並描述你想要達到的目標。如果可能的話舉一個例子。 _「我得到不能從節點轉換爲int&」_如果'V'類型爲'int',它將起作用。我會將我的答案更新爲MVCE –