问题描述
我在C ++中实现了双向链接列表的实现
在main.cpp中,我像这样将其他类的对象推入该列表
list.insertBack(ClassA(name,description));
但是在那之后,我需要更改此对象的某个字段,例如执行更改填充的方法。为此,我需要以某种方式从列表中访问该对象,就像处理常规数组(诸如a[i]
之类)一样。为此,我需要在List类中使用特殊的方法/函数。我该如何实施?
解决方法
您只需要为课程提供operator[]
:
template<class T>
class List {
// your private interface
public:
// your other public interface
T& operator[](unsigned int i)
{
Node* n = this->head;
for (; i>0; --i)
{
n = n->next;
}
return n->data;
}
};
然后您就可以像使用它一样简单地使用它
int main() {
List<double> l;
l.insertBack(0.0);
l.insertBack(1.0);
l.insertBack(2.0);
l.insertBack(3.0);
std::cout << l[2] << std::endl;
}
请注意,您可能还需要此功能的const
版本。这是demo。
注意:正如@Botje指出的那样,您可能还需要对输入内容进行完整性检查。如果i
等于或大于现有节点数,我的代码段将取消引用nullptr
,您将得到未定义的行为。