在c++中继承vector类时重载方括号

Overloading square brackets while inheriting vector class in c++?

本文关键字:重载 方括号 vector c++ 继承      更新时间:2023-10-16

我想从stl vector类继承一个叫做arithmelcevector的类。我的问题是方括号超载。下面是代码:

    template<class type>
type& ArithmeticVector<type>::operator[](int index) const{
    if(this->size()<=index || index < 0){
        throw string("Size Error!");
    }else{
        return vector<type>::operator[](index);
    }
}

给出错误:

将类型为int的引用绑定到类型为const int的值时,会删除限定符。

        return vector<type>::operator[](index);

我该如何修复它?

您应该删除const或添加const:

template <class type>
const type& ArithmeticVector<type>::operator[](int index) const
template <class type>
type& ArithmeticVector<type>::operator[](int index)