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
你能告诉我这个例子吗? –