lundi 24 février 2020

How to implement operator[] for a class which holds a std::vector

I'd like to override the [] operator for an object which holds a std::vector object (that is, have the subscripting act as though it were directly applied to the member vector). This is what I have so far

using namespace std;
#include <string>
#include <iostream>
#include <vector>

class VectorWrapper
{
public:
    VectorWrapper(int N): _N(N), _vec(N) {}

    ~VectorWrapper() {delete &_vec;}

    string operator[](int index) const
    {
        return _vec[index];
    }

    string& operator[](int index)
    {
        return _vec[index];
    }


private:
    int _N;
    vector<string> _vec;
};

int main()
{
    VectorWrapper vo(5);
    vo[0] = "str0";
    std::cout << vo[0];
}

Which upon running produces the following error

Process finished with exit code 11

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire