template <class TYPE>
class DList
{
//Declaring private members
private:
unsigned int m_nodeCount;
Node<TYPE>* m_head;
Node<TYPE>* m_tail;
public:
DList();
DList(DList<TYPE>&);
~DList();
unsigned int getSize();
void print();
bool isEmpty() const;
void insert(TYPE data);
void remove(TYPE data);
void clear();
Node<TYPE>* getHead();
...
TYPE operator[](int); //i need this operator to both act as mutator and accessor
};
我需要編寫一個模板功能,將做如下處理:C++ []索引運算符重載作爲accessor和mutator
// Test [] operator - reading and modifying data
cout << "L2[1] = " << list2[1] << endl;
list2[1] = 12;
cout << "L2[1] = " << list2[1] << endl;
cout << "L2: " << list2 << endl;
我的代碼着工作與
list2[1] = 12;
我得到錯誤C2106:'=':左操作數必須是l值錯誤。 我想[]操作才能夠讓列表2的第一個索引節點值12
我的代碼:
template<class TYPE>
TYPE DList<TYPE>::operator [](int index)
{
int count = 0;
Node<TYPE>*headcopy = this->getHead();
while(headcopy!=nullptr && count!=index)
{
headcopy=headcopy->getNext();
}
return headcopy->getData();
}
操作'[]'通常有兩個重載,沒有之一。你需要實現兩者。 [見示例](http://en.cppreference.com/w/cpp/container/vector/operator_at) – PaulMcKenzie
此外,如果'DList'作爲'const'傳遞,並且您試圖在任何方面使用'[]'。這就是爲什麼你需要第二次過載。 –
PaulMcKenzie
你能告訴我這個例子嗎? –