简体   繁体   English

如何为包含 std::vector 的类实现 operator[]

[英]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).我想为一个包含std::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?我究竟做错了什么?

You are trying to delete your member in the destructor.您正试图在析构函数中删除您的成员。 Only use delete on objects that you created with new .仅对使用new创建的对象使用delete Remove that destructor completely, the language will handle the destruction for you.完全删除那个析构函数,语言会为你处理破坏。

Also, your first index operator should return a const reference此外,您的第一个索引运算符应该返回一个常量引用

string const& operator[](int index) const

instead of a value.而不是一个值。

Furthermore, _N is an illegal name.此外, _N是非法名称。 You're not allowed to name things starting with an underscore followed by an uppercase letter.不允许以下划线开头后跟大写字母命名。

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

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