mardi 22 juin 2021

Error: Cannot Convert from Initializer List to Iterator [closed]

I have this code in C++ Visual Studio 2019 that uses a Ring class:

Ring.h

template <class T>
class Ring
{
private:
    T *m_values;
    int m_size;
    int m_pos;
public:
    class iterator;
    Ring(int size = 10) : m_size(size), m_values(NULL), m_pos(0)
    {
        this->m_values = new T[size];
    }
    ~Ring()
    {
        delete[] this->m_values;
    }
    int size() const
    {
        return this->m_size;
    }
    iterator& begin() const
    {
        return iterator(0, *this);
    }
    iterator& end() const
    {
        return iterator(this->m_size, *this);
    }
    void add(T value)
    {
        this->m_values[this->m_pos] = value;
        this->m_pos++;
        if (this->m_pos == this->m_size)
        {
            this->m_pos = 0;
        }
    }
    T& get(int pos) const
    {
        return this->m_values[pos];
    }
};

template <class T>
class Ring<T>::iterator
{
private:
    int m_pos;
    Ring m_ring;
public:
    iterator(int pos, Ring& obj) : m_ring(obj), m_pos(pos) {}
    iterator(const iterator& other) : m_ring(other.m_ring), m_pos(other.m_pos) {}
    iterator& operator++(int)
    {
        this->m_pos++;
        return *this;
    }
    iterator& operator++()
    {
        this->m_pos++;
        return *this;
    }
    T& operator*() const
    {
        return this->m_ring.get(this->m_pos);
    }
    bool operator!=(const iterator& other) const
    {
        return this->m_pos != other.m_pos;
    }
};

main.cpp

int main()
{
    Ring<std::string> textRing(3);
    textRing.add("one");
    textRing.add("two");
    textRing.add("three");
    textRing.add("four");
    for (std::string value : textRing)
    {
        std::cout << value << std::endl;
    }
    return 0;
}

When I try to run the code it always shows me the same error:

<function-style-cast>: cannot convert from 'initializer list' to 'Ring<std::string>::iterator" (Ring.h, Line 38).

What did I do wrong?

Aucun commentaire:

Enregistrer un commentaire