繁体   English   中英

动态泛型数组重载下标运算符[]?

[英]Dynamic generic array overload the subscript operator []?

您好,我希望能够从下标运算符访问索引。 但是我目前收到此错误:

Error   C2440   'return': cannot convert from 'T' to 'List<char> &' 

我也尝试过不同的东西,但我不知道该怎么做以及这个错误来自哪里? 如果有人可以检查出来,我将不胜感激。

问题是我得到这个列表我不明白为什么? 这是 function:

 List& operator[] (int index) {
        return first_cell[index];
    }

有完整的代码:

template<class T>
class List {

private:
    T* first_cell = nullptr;
    int size = 0; // currently occupied elements
    int capacity = 8; // size of the allocated memory

    void resize() {
        int new_cap = capacity * 2; // increased capacity
        T* new_arr = new T[new_cap]; // new arr with new capacity

        for (int k = 0; k < size; ++k) {
            new_arr[k] = first_cell[k]; // copy data from frist array
        }

        delete[] first_cell; // remove first array

        first_cell = new_arr;
        capacity = new_cap;
    }

public:
    List() {
        first_cell = new T[capacity]; // Declare the array in memory
    }

    List(const List& src)
        : size(src.size),
        capacity(src.capacity)
    {
        first_cell = new T[capacity];
        std::copy_n(src.first_cell, size, first_cell);
    }

    List(List&& src)
        : first_cell(src.first_cell),
        size(src.size),
        capacity(src.capacity)
    {
        src.first_cell = nullptr;
        src.size = src.capacity = 0;
    }

    ~List() {
        delete[] first_cell;
    }

    List& operator=(List rhs) {
        List temp(std::move(rhs));
        std::swap(first_cell, temp.first_cell);
        std::swap(size, temp.size);
        std::swap(capacity, temp.capacity);
        return *this;
    }

    // ToDo: ADD access operator

    List& operator[] (int index) {
        return first_cell[index];
    }

    void push_back(int number) {
        if (size == capacity) {
            resize();
        }
        first_cell[size] = number;
        ++size;
    }

    int length() {
        return size;
    }

    int first_index_of(int number) {
        for (int k = 0; k < size; k++) {
            
            if (number == first_cell[k]) {
                
                return k;
            }           
        }
        return -1;
    }

    void print(char symb) {
        for (int k = 0; k < size; ++k) {            
            std::cout << first_cell[k] << symb;
        }
    }
};

您正在尝试返回数组中的单个元素,因此您的operator[]需要返回对元素类型的引用,而不是对列表类型的引用:

T& operator[] (int index) {
    return first_cell[index];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM