簡體   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