繁体   English   中英

C ++矢量模板运算符[]

[英]C++ Vector Template operator []

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

我用插入函数制作了一个矢量模板,该函数将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];
}

注意:使用私有变量:大小,容量,数据(存储动态数组)我敢肯定我已经正确实现了add或push_back函数。 问题是,每当我尝试引出类似“ 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
      ]

应该有2个版本的operator[]

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

您拥有的是两者的怪异组合。

你也应该回来

return Data[index];

返回(*this)[index]; 将导致无限递归调用(嗯,不是无限的,在此之前您将获得stackoverflow)。

这里有三个问题:

  1. 运算符优先级。 *this[index]被解析为*(this[index]) ,而您的意思是(*this)[index]
  2. 您正在从const方法返回对数据的可变引用。
  3. operator[]的定义是循环的。 operator[]返回(*this)[index] operator[]将导致无限递归。

operator[]函数被声明为常量,即它不能更改Vector对象中的任何内容。 但是它返回一个引用,这意味着可以修改返回的值。 这两个相互矛盾。

这可以通过从函数末尾删除const或不返回引用来解决。

暂无
暂无

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

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