C++:向量<>的运算符[]重载

-1 c++ overloading operator-overloading operators stdvector

我正在尝试[]在向量上重载运算符.我试图让这个运算符在Matlab或Python中工作,用于负索引或大于矢量长度的索引.我的问题不是得到正确的结果,而是实际重载运算符,知道我将在重载代码中使用非重载运算符.我需要它用于特定类的向量,但如果它适用于任何类型它会更好vector.

现在我的代码是:header:

MyClass std::vector::operator[](std::vector<MyClass> const vector,int const idx) const;
Run Code Online (Sandbox Code Playgroud)

资源:

Myclass vector::operator[](vector<MyClass> const vector,int const idx) const {
    n=vector.size()
    if((idx>=0) && (idx<n)){
        return vector[idx];
    }
    else if(idx<0){
        return vector[n+idx%n]
    }
    else{
        return vector[idx%n]
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到错误:

error: 'template<class _Tp, class _Alloc> class std::vector' used without template parameters
error: non-member function 'MyClass operator[](std::vector<MyClass>, int)' cannot have cv-qualifier
error: 'MyClass operator[](std::vector<MyClass>, int)' must be a nonstatic member function
Run Code Online (Sandbox Code Playgroud)

如果这个问题已经讨论过了,我很抱歉,但是我找不到它......非常感谢你提前得到答案!

Vit*_*meo 5

您的错误与语法有关:

vector::operator[]
Run Code Online (Sandbox Code Playgroud)

应该

vector<MyClass>::operator[]
Run Code Online (Sandbox Code Playgroud)

但是,您不能随意重新定义您不拥有的类的运算符.您可以做的是创建自己的MyVector类,公开继承自vector:

struct MyVector : std::vector<MyClass>
{
    MyClass& operator[](std::size_t index)
    { 
        // ...
    } 
};
Run Code Online (Sandbox Code Playgroud)