【发布时间】:2017-12-02 22:44:52
【问题描述】:
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
};
我需要编写一个模板函数来执行以下过程:
// 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:'=':左操作数必须是左值错误。 我希望 [] 运算符能够使 list2 的第一个索引节点值为 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();
}
【问题讨论】:
-
运算符
[ ]通常有两个重载,而不是一个。您需要同时实现两者。 See example here -
另外,如果
DList<T>以const的形式传递并且您尝试在任何方面使用[ ],您的代码将不起作用。这就是为什么你需要第二个重载。 -
你能告诉我例子吗?
-
void SomeFunc(const DList<int>& d) { std::cout << d[0]; }-- 试试看。[ ]的所有功能都不起作用,即使您声称现在正在使用的功能也是如此。相反,您将收到编译器错误。要解决这个问题,您需要const重载版本。
标签: c++ indexing operator-overloading