C++ []索引运算符重载作为accessor和mutator
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();
}
回答:
我的代码斜面工作
list2[1] = 12;
我得到错误C2106:'=':左操作数必须是l值错误。我想 []操作才能够让列表2的第一个索引节点值12
在C++中,我们有所谓的Value Categories。您应该通过参考使操作员返回。
TYPE operator[](int);
到:因此,你的宣言,从改变
TYPE& operator[](int);
我假设headcopy->getData();
同样返回到一个非本地变量的引用。
由于PaulMcKenzie注意,你同样需要一个有const
this
,又名const
成员函数重载工作过载。因此,我们有:
TYPE& operator[](int); const TYPE& operator[](int) const;
见What is meant with "const" at end of function declaration?和Meaning of "const" last in a C++ method declaration?
以上是 C++ []索引运算符重载作为accessor和mutator 的全部内容, 来源链接: utcz.com/qa/258672.html