我正在尝试实现链表,但我对 operator[] 有一些问题
template <class T>
T& L1List<T>::at(int i){
L1Item<T> * pRet = this->_pHead;
int idx = 0;
while(pRet){
if(i != idx){
pRet = pRet->pNext;
idx++;
}else return (pRet->data);
}
}
template <class T>
T& L1List<T>::operator[](int i){
return at(i);
}
当我编译它时,它以 list->at(i) 运行,但以 list[i] 运行。 int a = 列表[i];错误是“无法在初始化时将 L1List'<'int> 转换为'int'”
最佳答案
如果list->at(i)
有效,这意味着 list
是指针,不是对象。因此,list[i]
评估为一个对象。这就是为什么 int a = list[i];
不起作用,这也解释了错误消息。您不能使用 L1List<int>
初始化 int
类型的对象.
你需要使用:
int a = (*list)[i];
或者让它变得非常复杂并使用:
int a = list->operator[](i);
关于时间:2019-05-08 标签:c++linkedliSTListoperator[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50616972/