C++ vector 模板运算符 []

标签 c++ vector operator-keyword ostream

首先我想说这是一项硬件作业,我只是对我面临的错误有疑问

我制作了一个带有插入函数的 vector 模板,该函数将 data_type 添加到动态数组的末尾。这是我目前拥有的。

// Insert the value at the specified index by moving the tail
// when Size = Capacity the Vector has to be reallocated first 
// to accomate the new element
void Insert(const DATA_TYPE& value, int index){

    // If the Capacity is not large enough then ...
    // allocate large vector
    if (Size >= Capacity){
        // 0. Let's boost the capacity
         Capacity += CAPACITY_BOOST;
        // 1. Allocate new larger vector
         DATA_TYPE* newData = new DATA_TYPE[Capacity];

        // 2. Copy from old Data into the newData
         for( int i=0; i< Size; i++)
                newData[i] = Data[i];

        // 3. Delete the old Data
         delete[] Data;

        // 4. Replace old Data-pointer with the newData pointer
        Data = newData;
    }

    // Move the tail
    for(int i=index; i<Size;i++){
        Data[i+1] = Data[i];
    }

    // Insert
    Data[index] = value;
    Size++;

}
DATA_TYPE& operator[] (int index) const{
    return *this[index];
}

注意:使用私有(private)变量:大小、容量、数据(存储动态数组) 我很确定我已经正确实现了 add 或 push_back 函数。问题是每当我尝试 cout 诸如“cout << a[1];”之类的东西时,我都会收到错误消息。

while compiling class template member function 'int &Vector<DATA_TYPE>::operator [](int) const'
      with
      [
          DATA_TYPE=int
      ]
see reference to class template instantiation 'Vector<DATA_TYPE>' being compiled
     with
     [
          DATA_TYPE=int
      ]
error C2440: 'return' : cannot convert from 'const Vector<DATA_TYPE>' to 'int &'
    with
     [
        DATA_TYPE=int
      ]

最佳答案

operator[] 应该有两个版本:

const DATA_TYPE& operator[] (int index) const;
DATA_TYPE& operator[] (int index);

你所拥有的是两者的奇怪组合。

你也应该回来

return Data[index];

返回 (*this)[index]; 会导致无限递归调用(好吧,不是无限,你会在这之前得到一个 stackoverflow)。

关于C++ vector 模板运算符 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12803387/

相关文章:

C++::vector如何保存自己的类

c++ - 在 C++ 的函数模板中使用重载的 operator+

r - 在实例化时为向量分配名称

c++ - const int 定义的变量是在编译时确定的吗?

python - 使用 Pybind11 将 C++ 扩展到 Python

c++ - 为什么我会收到静态成员变量的 "undefined reference"链接错误?

python - 以与轴的纵横比一致的物理单位重新缩放箭矢箭头

c++ - 未能重载运算符<< (c++)

c++ - 如何修改给定的类以使用 const 运算符

c++ - 声明带/不带大括号的 C++ 对象之间的区别