时间:2019-05-08 标签:c++linkedliSTListoperator[]

标签 c++ operators

我正在尝试实现链表,但我对 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/

相关文章:

swift - Swift 中的 &<< 和 << 运算符有什么区别?

c++ - XOR 运算符与 std::ostream 运算符

c++ - const 变量的引用运算符 "&"的结果是什么?

python - PyImport_Import 找不到模块

c++ - 读取数据 RS232 无需轮询

c++ - 在 macOS 中使用 omp.h 的正确方法

c++ - AppCode - 在 Objective-C 项目中调试 C++ 程序?

C++ vector 矩阵的 Boost 序列化

ios - 请在 Apple SpriteKit 示例代码中解释 uint32_t 和 0x1 << 0

Java << 运算符